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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With