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.
second approach is working fine .
Thanks :)
Thanks! The second method helped.
The first method throws error for me.. “multiple selections not set”.
RP.
Thanks for sharing nice info.
Easy way is DropDownList1.Items.FindByText( defaultText).selected = true
2nd is good !!! thanx
2nd approach is best!
Thanks you
Dude, the second approach it is way better than any other I have googled for.
Thanks