Recently I had an issue where I just could not set a drop down list’s selected value from the code behind. I set other drop down list’s selected values from the code behind with no problem. Just this one was giving me grief. So here is how I set the values normally (the drop down lists are inside a formview):
VB.Net
Dim ddl As DropDownList
ddl = fvTest.FindControl("ddlWorks")
ddl.SelectedValue = 5
C#
DropDownList ddl;
ddl = (DropDownList)fvTest.FindControl("ddlWorks");
int j = 5;
ddl.SelectedValue = Convert.ToString(j);
Again I used this code for several different drop down lists. For the one that gave me problems I just used this:
VB.Net
Dim ddl2 As DropDownList
ddl2 = fvTest.FindControl("ddlProblem")
Dim i As Integer = 9
For Each li As ListItem In ddl2.Items
If li.Value = i Then
li.Selected = True
Exit For
End If
Next
C#
DropDownList ddl2;
ddl2 = (DropDownList)fvTest.FindControl("ddlProblem");
int i = 9;
foreach (ListItem li in ddl2.Items)
{
if (li.Value == Convert.ToString(i))
{
li.Selected = true;
break;
}
}
Technorati Tags:
vb.Net,
Csharp