Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'myObject' does not contain a property with the name 'ID' (Not a typo) [duplicate]

Tags:

c#

asp.net

I am building an ASP.NET C# website, and I have a dropdownlist that I am binding to a list of objects that I have created. The code that binds the dropdownlist looks like this:

protected void PopulateDropdownWithObjects(DropDownList dropdownlist, List<myObject>() myObjects)
{
    dropdownlist.DataValueField = "ID";
    dropdownlist.DataTextField = "Name";
    dropdownlist.DataSource = myObjects;  // my code fails here
    dropdownlist.DataBind();
}

However, when it hits the 3rd line within the method, an exception is thrown:

DataBinding: 'myObject' does not contain a property with the name 'ID'.

However, I can clearly see the myObject.ID value while I debug: I can access it in the Immediate window, it's public, it isn't null, and I spelled it correctly and with the proper case:

public class myObject
{
    public int ID;   // see? "ID" is right here!
    public string Name;

    public myObject(
        int id,
        string name
        )
    {
        this.ID = id;
        this.Name = name;
    }
}

Is there anything else that can cause this error?

like image 639
Chris Avatar asked Aug 30 '13 18:08

Chris


1 Answers

Your code will not work, because ID is a field, not a property.

If you change your class, as shown below, the code will work as intended:

public class myObject
{
    public int ID    // this is now a property
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }

    public myObject(
        int id,
        string name
        )
    {
        this.ID = id;
        this.Name = name;
    }
}
like image 104
Chris Avatar answered Sep 19 '22 15:09

Chris