C# “Object reference not set to an instance of an object” Get Type / Get Property [duplicate]

China☆狼群 提交于 2019-12-12 03:37:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!