Jul 4, 2013

How to bind a List to an ASP.Net DropDownList

This code shows how you can build a custom class (Person for the demo), and then take a System.Collections.Generic.List, fill it with Person's and bind it to an ASP.Net DropDownList control.


First we need a Person class. I need to override the ToString() function if we want it to bind automatically without setting the DataTextField of the DropDownList. Also note that if we do want to set the DataTextField and DataValueField, then we have to have public properties. The following class will work either way we choose to bind it to the DropDownList.
 

public class Person
{
    private int _ID;
    private string _Name;
    private string _Color;
    public override string ToString()
    {
        return _Name;
    }
    // Properties   
    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
    public string Color
    {
        get { return _Color; }
        set { _Color = value; }
    }   
}
Ok so now we need a function in our ASP.net page that loads a <List> of Person's into the DropDownList.

Option 1) We set the DataTextField and the DataValueField. This relies on the public properties in Person

    protected void LoadList()
    {       
        List<Person> myPList = new List<Person>();

        Person p1 = new Person();
        p1.ID = 1;
        p1.Name = "Bob";
        p1.Color = "Blue";

        Person p2 = new Person();
        p2.ID = 2;
        p2.Name = "Joe";
        p2.Color = "Green";

        myPList.Add(p1);
        myPList.Add(p2);

        this.DropDownList1.DataSource = myPList;
        this.DropDownList1.DataTextField = "Color";
        this.DropDownList1.DataValueField = "ID";
        this.DropDownList1.DataBind();       
    }
The HTML output will be:
 <select name="DropDownList1" id="DropDownList1">
 <option value="1">Blue</option>
 <option value="2">Green</option>
 </select>



Option 2) Not setting the DataTextField and the DataValueField. This relies on the 'ToString() override in Person bind the text field.

protected void LoadList()
    {       
        List<Person> myPList = new List<Person>();

        Person p1 = new Person();
        p1.ID = 1;
        p1.Name = "Bob";
        p1.Color = "Blue";

        Person p2 = new Person();
        p2.ID = 2;
        p2.Name = "Joe";
        p2.Color = "Green";

        myPList.Add(p1);
        myPList.Add(p2);

        this.DropDownList1.DataSource = myPList;       
        this.DropDownList1.DataBind();       
    }

The HTML output will be the ToString() value for both the text and value.
<select name="DropDownList1" id="DropDownList1">
 <option value="Bob">Bob</option>
 <option value="Joe">Joe</option>
</select>

No comments:

Post a Comment