11

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?

Chris
  • 3,328
  • 1
  • 32
  • 40

1 Answers1

42

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;
    }
}
Chris
  • 3,328
  • 1
  • 32
  • 40
  • 25
    Are you talking to yourself in second person? – Garrison Neely Aug 30 '13 at 19:02
  • 1
    @GarrisonNeely Yea, why would anyone [ever](http://stackoverflow.com/questions/3390896/need-to-transform-a-rectangles-color-in-windows-phone-7) use "you" when answering their [own](http://stackoverflow.com/questions/7920579/efficiently-propagating-interface-changes-in-visual-studio) post? [;)](http://data.stackexchange.com/stackoverflow/query/133843) – Scott Chamberlain Aug 30 '13 at 20:34
  • 2
    Stalker. My answers use "you" instead of "one". This answer doesn't use "you" in that way. Typically a user answering his/her own question will acknowledge it in some way. – Garrison Neely Aug 30 '13 at 20:38
  • 2
    Often after banging on my head on something for days [I will post a question with a immediate answer](http://stackoverflow.com/questions/11346554/can-i-use-extension-methods-and-linq-in-net-2-0-or-3-0/11346555#11346555) just to stop the suffering of other people who may go though the same issue as me (however I agree he should of checked for a duplicate first). – Scott Chamberlain Aug 30 '13 at 20:43