Apr 29, 2011

Programmatically select an item in asp.net dropdownlist by text

Yesterday, I got following question:

Q: I have dropdownlist(say country) and the datasource is datatable having countryname, countrycode columns. I have to select proper country in dropdownlist from the text. I don't have value(countrycode) to select. How can I do this?


It is common question for the beginners. To understand this,

consider the following code:

//Dummy DataTable
        DataTable dt = new DataTable();
        for (int i = 1; i <= 10; i++) {
            DataRow dr = dt.NewRow();
            dr[0] = "Country"+i.ToString();
            dr[1] = i;
        //Configure DropDownList
        DropDownList1.DataTextField = "CountryName";
        DropDownList1.DataValueField = "CountryCode";
        DropDownList1.DataSource = dt;
        //default value
        string defaultText = "Country3";

Our object is to select defaultText in DropDownList1.

First Way(Old Way):

        //First Way
        foreach (ListItem item in DropDownList1.Items) {
            if (item.Text == defaultText) {
                item.Selected = true;

Second Way:

Another way is to set selectedindex of dropdownlist. see following:

DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf( DropDownList1.Items.FindByText( defaultText));

To get SelectedIndex, IndexOf method is used but it takes ListItem as argument. So, FindByText method is used to get corresponding ListItem.

Hope, It helps.