【发布时间】:2021-03-25 22:56:07
【问题描述】:
我在将字节数组的图像从数据库检索到 WPF 页面中的图片框时遇到一些问题。这是我从字节转换为图像的代码:
private BitmapImage GetBitmapImageFromBytes(byte[] bytes)
{
BitmapImage btm;
using(MemoryStream stream = new MemoryStream(bytes))
{
btm = new BitmapImage();
btm.BeginInit();
btm.StreamSource = stream;
btm.CacheOption = BitmapCacheOption.OnLoad;
btm.EndInit();
btm.Freeze();
}
return btm;
}
我在从数据库读取数据的SQlDataReader 中调用此方法时遇到问题。这是下面的代码:
private void StudentRegistrationForm_Loaded(object sender, RoutedEventArgs e)
{
try
{
StudentConn = new
SqlConnection(ConfigurationManager.ConnectionStrings["SchoolDB"].ConnectionString);
StudentCmd = new SqlCommand();
StudentCmd.Connection = StudentConn;
StudentCmd.CommandType = CommandType.StoredProcedure;
StudentCmd.CommandText = "spStudent_GetAll";
StudentConn.Open();
studentReader = StudentCmd.ExecuteReader();
if (studentReader.Read())
{
TxtbID.DataContext = (int)studentReader["Id"];
TxtLastName.DataContext = (string)studentReader["LastName"];
TxtFirstName.DataContext = (string)studentReader["FirstName"];
TxtEmail.DataContext = (string)studentReader["Email"];
CboGender.SelectedItem = (string)studentReader["Gender"];
DtpDateOfBirth.DataContext = (DateTime)studentReader["DateofBirth"];
DtpDateRegistered.DataContext = (DateTime)studentReader["DateRegistered"];
TxtPhone.DataContext = (string)studentReader["MobileNumber"];
TxtComment.DataContext = (string)studentReader["Notes"];
CboReligion.SelectedItem = (string)studentReader["Religion"];
imgprofilePicture.DataContext = (Image)studentReader[GetBitmapImageFromBytes(ImageArray)];
CboSpecialAttention.SelectedItem = (string)studentReader["SpecialAttention"];
TxtGuardianID.DataContext = (int)studentReader["GuardianID"];
}
}
catch (Exception ex)
{
if (ex is SqlException || ex is SystemException || ex is NullReferenceException)
{
MessageBox.Show(ex.Message, "Error Establishing Connection to Student Data Service", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
finally
{
StudentConn.Close();
StudentConn.Dispose();
studentReader.Close();
StudentCmd.Dispose();
}
SetState("View");
}
我迷路了,我不知道我做错了什么,我只是得到了这么多不同类型的异常。请有人帮我检查代码并纠正我。
【问题讨论】:
-
设置所有这些控件的 DataContext 属性看起来很奇怪。您可以直接设置它们的 Text(或类似)属性,或者将它们的公共父元素的 DataContext 设置为您在从 db 读取数据时创建的数据对象,并将 UI 元素属性绑定到数据的属性对象。
标签: c# sql-server wpf sqldatareader