Groups | Blog | Home
all groups > dotnet framework > july 2004 >

dotnet framework : Binding an ArrayList of custom objects to a dropdownlist


David Guthu
7/31/2004 10:57:03 AM
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!

--
Bharat Biyani
8/1/2004 10:13:01 PM
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).

--
Bharat Biyani (bsb@orcim.com)
http://www.orcim.com



[quoted text, click to view]
AddThis Social Bookmark Button