To understand this, consider the following code:
//Dummy DataTable
DataTable dt = new DataTable();
dt.Columns.Add("EmployeeName");
dt.Columns.Add("EmployeeId");
for (int i = 1; i <= 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = "Name" + i.ToString();
dr[1] = i;
dt.Rows.Add(dr);
}
//Configure DropDownList
DropDownList1.DataTextField = "EmployeeName";
DropDownList1.DataValueField = "EmployeeId";
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
//default value
string defaultText = "Name5";
Approach 1:
foreach (ListItem item in DropDownList1.Items)
{
if (item.Text == defaultText)
{
item.Selected = true;
break;
}
}
Approach 2:
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(defaultText));
Happy Coding!!
0 Comment(s)