office1_screen
April 29th, 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?

Solution:

It is common question for the beginners. To understand this,
consider the following code:

//Dummy DataTable
        DataTable dt = new DataTable();
        dt.Columns.Add("CountryName");
        dt.Columns.Add("CountryCode");
        for (int i = 1; i <= 10; i++) {
            DataRow dr = dt.NewRow();
            dr[0] = "Country"+i.ToString();
            dr[1] = i;
            dt.Rows.Add(dr);
        }
        //Configure DropDownList
        DropDownList1.DataTextField = "CountryName";
        DropDownList1.DataValueField = "CountryCode";
        DropDownList1.DataSource = dt;
        DropDownList1.DataBind();
        //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;
                break;
            }
        }

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.

  • Musthaan

    Thanks

  • Ricardo

    Dude, the second approach it is way better than any other I have googled for.

  • Juned

    2nd approach is best!
    Thanks you

  • Samson

    2nd is good !!! thanx

  • Premkumar

    Easy way is DropDownList1.Items.FindByText( defaultText).selected = true

  • Chandradev Prasad

    Thanks for sharing nice info.