Search code examples
vb.netwebformsselectedvalue

SelectedValue in DropDownList unable to select any value (VB.Net, Asp.Net)


I have a DropDownList inside my form and I added those list using code behind like this :

With DropDownList1
    .Items.Clear()
    .Items.Add(New ListItem(" --- None --- ", ""))
    .Items.Add(New ListItem("01", "1"))
    .Items.Add(New ListItem("02", "2"))
End With

So here are my coding that doing the action when value inside the DropDownList is selected :

If Not DropDownList1.SelectedValue = "" Then
    If DropDownList1.SelectedValue = "1" Then
        ' Some statement goes here
    ElseIf DropDownList1.SelectedValue = "2" Then
        ' Some statement goes here
    End If
End If

So the problem here is, when I run my web and select value from list, it select nothing. The result is always DropDownList1.SelectedValue = "". I wonder why. Somebody guide me please. Thank you.


Solution

  • The value of your DropDownList is initialized every time when your form loads (I assume that you placed the population in form load) or do a PostBack, thus resetting the value of the DropDownList to "". Try covering the DropDownList population in a IsPostBack condition. Like this:

    If Not IsPostBack Then
         With DropDownList1
             .Items.Clear()
             .Items.Add(New ListItem(" --- None --- ", ""))
             .Items.Add(New ListItem("01", "1"))
             .Items.Add(New ListItem("02", "2"))
         End With
    End If