我在SQL Server中创建了一个表:
它的名字是[dbo].[Family_Tree]
ID NodeName
1 John
2 George
3 Mike
4 Sandra
5 Jasmine
6 Lucy
我创建了一个Vb.net应用程序,我希望在Combobox或列表框中显示这些名称
以下是填充列表框的代码:
Using con As New SqlConnection(My.Settings.ConnString)
Dim DT As New DataTable
Dim Adp As New SqlDataAdapter
With Adp
.SelectCommand = New SqlCommand("Select NodeName , ID From Family_tree", conn)
.Fill(DT)
End With
With ListBox1
.DataSource = DT
.DisplayMember = "NodeName"
.ValueMember = "ID"
End With
End Using
显示名称并且没有任何问题,我想要的是当我选择任何名称时,列表框会返回其相应的ID .ValueMember = "ID"
,我在msgbox MsgBox(ListBox1.ValueMember)
中对它进行了测试,它总是返回ID,那么如何让它理解这是一个不是字符串的列?
提前感谢...
答案 0 :(得分:0)
你可以使用ListBox.SelectedItem
,f.e。在它的SelectedIndexChanged
事件:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim curItem As DataRowView = TryCast(ListBox1.SelectedItem, DataRowView)
If curItem IsNot Nothing Then
Dim id = curItem.Row.Field(Of Int32)("ID")
End If
End Sub
答案 1 :(得分:0)
要获取您编写的列表框中当前显示项目的值
if ListBox1.SelectedValue IsNot Nothing Then
Dim v = Convert.ToInt32(ListBox1.SelectedValue)
.......
获取或设置由...指定的成员属性的值 ValueMember属性。