troubleshooting Question

Setting an ASP:DropDownList.SelectedIndex

Avatar of Psyberion
PsyberionFlag for United Kingdom of Great Britain and Northern Ireland asked on
.NET Programming
8 Comments1 Solution1750 ViewsLast Modified:
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?
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 8 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 8 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros