所以我有这些代码可以获取用户信息。
注意:注释行是我已尝试过的内容。
代码:
public UserInfo GetUserCredentials(string usernameParameter, string passwordParameter)
{
UserInfo getInfo = new UserInfo();
try
{
accessToDatabase.OpeningDatabase();
String query = "SELECT * FROM Users where Username=@Username AND Password=@Password";
SqlCommand sqlCmd = accessToDatabase.Command(query);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("@Username", usernameParameter);
sqlCmd.Parameters.AddWithValue("@Password", passwordParameter);
SqlDataReader oReader = sqlCmd.ExecuteReader();
byte[] pictureIdByte;
Image pictureIdImg = null;
while (oReader.Read())
{
getInfo.Username = oReader["Username"].ToString();
getInfo.Password = oReader["Password"].ToString();
getInfo.Role = oReader["Role"].ToString();
getInfo.Firstname = oReader["Firstname"].ToString();
getInfo.Lastname = oReader["Lastname"].ToString();
getInfo.Status = Convert.ToInt32(oReader["Status"]);
getInfo.Gender = oReader["Gender"].ToString();
getInfo.Birthday = oReader["Birthday"].ToString();
getInfo.Email = oReader["Email"].ToString();
getInfo.Address = oReader["Address"].ToString();
getInfo.City = oReader["City"].ToString();
getInfo.Country = oReader["Country"].ToString();
getInfo.Mobilenumber = oReader["Mobile"].ToString();
pictureIdByte = (byte[])(oReader["PictureID"]);
if (pictureIdByte == null)
{
getInfo.PictureID = pictureIdImg;
}
else
{
//MemoryStream stream = new MemoryStream(pictureIdByte);
//getInfo.PictureID.Source = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
//var pictureIdVar = new BitmapImage();
//using (var memStream = new MemoryStream(pictureIdByte))
//{
// memStream.Position = 0;
// pictureIdVar.BeginInit();
// pictureIdVar.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
// pictureIdVar.CacheOption = BitmapCacheOption.OnLoad;
// pictureIdVar.UriSource = null;
// pictureIdVar.StreamSource = memStream;
// pictureIdVar.EndInit();
//}
//pictureIdVar.Freeze();
//getInfo.PictureID.Source = pictureIdVar;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
accessToDatabase.ClosingDataBase();
}
return getInfo;
}
我有这个主窗口,它有一个图像,我从xaml设计中删除并拖动。使用后面的代码,我尝试设置源代码,但每当我尝试登录时,它给我一个错误:
System.NullReferenceException:'对象引用未设置为对象的实例。'
MyThesisProject.Model.UserInfo.PictureID.get
返回null。
这是主窗口xaml背后的代码:
public partial class MainWindow : Window
{
public MainWindow(UserInfo userLoginDetails)
{
InitializeComponent();
imgTest.Source = userLoginDetails.PictureID.Source;
}
}
我不知道哪里出错了,我尝试使用注释行,但仍然是null的相同错误。
答案 0 :(得分:0)
您的UserInfo类中不应该有Image
个元素。
将PictureID
属性的类型更改为ImageSource
public class UserInfo
{
...
public ImageSource PictureID { get; set; }
...
}
并设置其值如下:
if (pictureIdByte != null)
{
using (var stream = new MemoryStream(pictureIdByte))
{
getInfo.PictureID = BitmapFrame.Create(stream,
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
}
在MainWindow构造函数中,像这样设置Image的Source:
imgTest.Source = userLoginDetails.PictureID;