简体   繁体   中英

Populate listbox with alias values using SQL select statment

I have two columns in MS SQL table (ID, and Name) that I want to use to populate a list box with. I would like to show the Name values (as alias?) in the list box, however when the user selects the item I want the ID value to be returned not the Name value. My code below just adds the values into the list box from the Name column.

 Me.listName.Items.Clear()

 Dim strName As String  = "select SetName from " & tb

 Dim con As String = sConnectionString
 Dim com As New SqlCommand(strServiceType, New SqlConnection(con))
 com.Connection.Open()

 Dim dr As SqlDataReader
 Dim ColumnValue As String = Nothing

 dr = com.ExecuteReader
 While dr.Read
   ColumnValue = (dr.GetValue(0)).ToString
   listName.Items.Add(ColumnValue)
   listName.Sorted = True
 End While

 com.Connection.Close()

I'm not sure how to apply the logic above to get the associated ID value besides running another select statement on the list box SelectedIndexChanged event.

Thank you

If I'm not mistaken, you simply need to edit your sql to pull both ID and Name, then edit your addition of an item to your list box to add a new list item instead.

ie

listName.Items.Add(New ListItem("TEXT","VALUE"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM