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.