Binding an ArrayList of custom objects to a dropdownlist

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How do I bind an arraylist of custom objects to a dropdownlist and set the datavaluefield and datatextfields?

Let's say I have an array of custom 'Person' objects.

public class Person
{
public string FirstName;
public string LastName;
.....
}

I want to bind an array of Person objects and use the DataTextField and DataValue field of the DropDown to bind:
ie:

....
ddList.DataSource = PersonObjectArray()
ddList.DataTextField = "FirstName";
ddList.DataValueField = "LastName"; ddList.DataBind();



Can this be done?
I've tried creating a PersonCollection class which inherits ArrayList but I'm still unsure how to access the properties of the objects within the arraylist to set the above values. Please help!
 
Hi David,

Expose the member variables of the object that you would like to bind to the combobox as properties.

Then set :
combobox.datasource= <array name variable>
combobox.datatextfield= <property to display>
combobox.datavaluefield=<property to be used as value>

eg:
ArrayList userlist=new ArrayList();
userlist.Add(new User("John",1));
userlist.Add(new User("Johnny",2))
userlist.Add(new User("Jenny",3))
ddl1.DataSource=userlist;
ddl1.DataTextField="UserName";
ddl1.DataValueField="Id";
ddl1.DataBind();

In the above eg. User is an object which exposes the UserName and Id properties which are bound to the dropdownlist (ddl1).
 
Back
Top