I have a bound DropDownList in an ASP Webapplication for which I need to set its' SelectedIndex and/or SelectedValue property programmatically in the VB.NET code behind.
e.g.
myDDL.DataSource = myDataSource
myDDL.DataTextField = "items"
myDDL.DataValueField = "values"
DataBind()
'Where myVal is the value of an item in the DropDownList
'Selecting via SelectedIndex:
For i = 0 To myDDL.Items.Count - 1
If myDDL.Items(i).Value = myVal Then
myDDL.SelectedIndex = i
End If
Next
'Selecting via SelectedValue:
myDDL.SelectedValue = myVal
Now these 2 methods do set the properties - SelectedIndex and SelectedValue, but since the control is already rendered the item for 'myVal' does not show in the control. Instead I get the first item in the controls list, as if no selection has been made.
If I move the DataBind() to after setting the SelectedIndex or SelectedValue it resets them so that nothing is selected, so again I get the first item in the DropDownList showing.
How can I select an item from the DropDownList programmatically so that it shows the item as being selected in the control?
myDDL.SelectedIndex = myDDL.Items.IndexOf(myDDL.