Getting te ID of a Selected Item in a dropdownlist.

  • Thread starter Thread starter Rob Venable
  • Start date Start date
R

Rob Venable

Hi all,
Can anyone tell me how to retrieve the ID of a selected item from a
DropDownList. My query brings back the ID and value and I cycle through
the .Read Method to add items to the DropDownList.
e.g.
While dr.Read
DDL.Items.Add(dr("value"))
End While

I can do it if I use this method:
DDL.DataSource = dr
DDL.DataTextField = "value"
DDL.DataValueField = "id"
DDL.DataBind()

and then refer the the DataValueField to get the ID.

This would be the easy way but I have to do it by adding items to the
DDL.
Is there a property I can set to make it equal to the ID and then be
able to retrieve it?

Thanks

Rob
 
Hey Rob,

Is it adding the list items to the ddl that is giving you trouble? If so,
here's a way to add them via the reader and display the ID when the ddl is
changed.

Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
If Not IsPostBack Then
Dim myCMD As SqlCommand = _
New SqlCommand _
("SELECT CategoryID, CategoryName FROM Categories", _
SqlConnection1)
SqlConnection1.Open()
Dim dr As SqlDataReader = myCMD.ExecuteReader()
Dim lstItem As ListItem
While dr.Read
lstItem = New ListItem
lstItem.Text = dr.Item("CategoryName")
lstItem.Value = dr.Item("CategoryID")
DropDownList1.Items.Add(lstItem)
End While
dr.Close()
SqlConnection1.Close()
End If
End Sub
Private Sub DropDownList1_SelectedIndexChanged _
(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles DropDownList1.SelectedIndexChanged
Label1.Text = DropDownList1.SelectedItem.Value.ToString
End Sub

<P>
<asp:DropDownList id="DropDownList1" runat="server"
AutoPostBack="True"></asp:DropDownList></P>
<P>
<asp:Label id="Label1" runat="server">Label</asp:Label></P>


Ken
MVP [ASP.NET]
 
Thanks Ken,
That works fine but I still have one little problem. I need to add a
blank entry in my dropdownlist because this select box is not a
mandatory field on my form.
If I instantiate the listitem inside my while loop, how can I add a
blank line at the top?

Thanks for your help.

Rob
 
Rob,

This is the code you need.

DropDownlist.Items.Insert(0,new ListItem(" "," "));

This will add a blank item to the first position of the drop down list.

Ragards,

Marshal Antony

http://dotnetmarshal.com
 
Back
Top