问题
Hi guys I'm receiving an error: "Object reference not set to an instance of an object". I'm not quite sure why... Here's the code:
public void LoadUserContacts(ListBox FriendsLb)
{
FriendsLb.DisplayMember = "Display";
var query = from o in Globals.DB.Friends
where o.UserEmail == Properties.Settings.Default.Email
select new
{
FirstName = o.FirstName,
LastName = o.LastName,
Email = o.Email,
Display = string.Format("{0} {1} - ({2})", o.FirstName, o.LastName, o.Email),
};
FriendsLb.DrawMode = DrawMode.OwnerDrawVariable;
foreach (object contact in query.ToList())
{
string details = query.GetType().GetProperty("Display").ToString();
FriendsLb.Items.Add(new Contacts(Properties.Resources.avatar, details));
FriendsLb.DrawItem += FriendsLb_DrawItem;
FriendsLb.MeasureItem += FriendsLb_MeasureItem;
}
}
Which code is causing the error:
string details = query.GetType().GetProperty("Display").ToString();
Any ideas? I'm trying to get the display property from the query:
Display = string.Format("{0} {1} - ({2})", o.FirstName, o.LastName, o.Email),
回答1:
You are trying to get the type of the query, and then the property of "Display" of the type, not the return value of the column in the database
The type of the query will not have that the property "display". You need to do something more like:
string property = contact.GetProperty("Display", typeof(string));
string details = property.Name;
I hope it puts you on the right track.
Also, set a breakpoint at that row to see what part of the line is a null reference to easily pinpoint where where problem is.
来源:https://stackoverflow.com/questions/38173237/c-sharp-object-reference-not-set-to-an-instance-of-an-object-get-type-get-pr