Thursday, April 19, 2012

Binding a C# List to a DropDownList control


Binding a C# List to a DropDownList control

In general we use a DataTable or a DataReader to bind data to a DropDownList control, today we shall see on how to bind an object of type List to a DropDownList control.

To know more about the List object refer to the post C# List  

First let us create a class whoose objects will be stored in the List, here is the code for the class.

public class clsCountry
{
    public string _CountryCode;
    public string _CountryName;
    //
    public clsCountry(string strCode, string strName)
    {
        this._CountryCode = strCode;
        this._CountryName = strName;
    }
    //
    public string CountryCode
    {
        get {return _CountryCode;}
        set {_CountryCode = value;}
    }
    //
    public string CountryName
    {
        get { return _CountryName; }
        set { _CountryName = value; }
    }
}

Next, let us create a list of objects based on our class clsCountry and store them in a List object. Here is the code for the List

List<clsCountry> lstCountry = new List<clsCountry>();
lstCountry.Add(new clsCountry("USA", "United States"));
lstCountry.Add(new clsCountry("UK", "United Kingdon"));
lstCountry.Add(new clsCountry("IND", "India"));

Finally we shall bind the List object lstCountry to a DropDownList control. Here the code to bind the data.

drpCountry.DataSource = lstCountry;
drpCountry.DataValueField = "CountryCode";
drpCountry.DataTextField = "CountryName";
drpCountry.DataBind();

Notice that the DataValueField and DataTextField property of the DropDownList control are mapped to the Properties of the class CountryCode and CountryName, hence make sure to create properties for every member of the class so that they can be used while binding the data to controls.

That’s it we have bound the contents of a List object to a DropDownList control.

Search Flipkart Products:
Flipkart.com