C# “Object reference not set to an instance of an

2019-09-02 07:48发布

This question already has an answer here:

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条回答
Explosion°爆炸
2楼-- · 2019-09-02 08:22

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.

查看更多
登录 后发表回答