Abigail Abigail - 5 months ago 28
Vb.net Question

Get the value of selected item in dropdownlist

I added Item in

dropdownlist
and when I select the Item I added, it does not show up in
Label1
. Here is my code:

ASPX

<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:DropDownList ID="drpOne" runat="server" AutoPostBack="true">
</asp:DropDownList>


VB

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

con.Open()
If Not IsPostBack Then
Dim Sql = "SELECT College FROM College"
cmdAdd = New SqlDataAdapter(Sql, con)
Dim ds As New DataSet()
cmdAdd.Fill(ds)

drpOne.DataSource = ds
drpOne.DataTextField = "College"
drpOne.DataValueField = "College"
drpOne.DataBind()
drpOne.Items.Insert(0, New ListItem("Please select College", ""))
drpOne.SelectedItem.Value = "Please select College"
drpOne.Items.Insert(0, New ListItem("All", ""))
end if
End Sub

Protected Sub drpOne_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpOne.SelectedIndexChanged
Label1.Text = drpOne.SelectedItem.Value
End Sub

Answer

i haven't checked the code, but try it this way

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    con.Open()
    If Not IsPostBack Then
        Dim Sql = "SELECT College FROM College"
        cmdAdd = New SqlDataAdapter(Sql, con)
        Dim ds As New DataSet()
        cmdAdd.Fill(ds)

        drpOne.AppendDataBoundItems = true
        drpOne.Add(New ListItem("Please select College", ""))//You have passed "Please select College" as text and "" as value in ListItem
        drpOne.Add(New ListItem("All", ""))

        drpOne.DataSource = ds
        drpOne.DataTextField = "College"
        drpOne.DataValueField = "College"
        drpOne.DataBind()

        drpOne.Items.FindByText("Please select College").Selected = true
 end if
End Sub

Protected Sub drpOne_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpOne.SelectedIndexChanged
    Label1.Text = drpOne.SelectedItem.Value
End Sub
Comments