office1_screen

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.

 

Related posts:

  1. jQuery: Common Operations on DropdownList (Combobox)
  2. Create Dynamic DropDownLists in asp.net
  3. Retrieve value of Dynamic controls in asp.net
  4. Adding Gridview nested in Repeater in ASP.NET 2.0
  5. Sharepoint search in document library/list programmatically (using C#)
  6. Copy/Extract HTML Dropdownlist Options in Plain Text
  7. Display Hierarchical Data with TreeView in ASP.NET 2.0

Comments:  4

  • 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