绑定两个Comboboxes并在VB.NET中保持它们同步

时间:2016-08-05 07:26:13

标签: vb.net combobox

我正在Vb.net开发一个销售点软件。我想渲染绑定Comboboxes并保持它们同步的功能。例如:ComboBox1显示" Book_Name"和Combobox2显示" Book_Code"。一旦" Book_Name"用户在Combobox1中选择,Combobox2必须自动显示相应的" Book_Code"。 任何人都可以建议我在VB.NET中实现这个功能的编程代码吗?

3 个答案:

答案 0 :(得分:0)

您只需将两个控件绑定到同一数据源,例如

myBindingSource.DataSource = myDataTable

With ComboBox1
    .DisplayMember = "BookName"
    .ValueMember = "BookId"
    .DataSource = myBindingSource
End With

With ComboBox2
    .DisplayMember = "BookCode"
    .ValueMember = "BookId"
    .DataSource = myBindingSource
End With

答案 1 :(得分:0)

您应该将两个组合框绑定到同一个BindingSource实例。 BindingSource将自己的DataSource属性设置为您的DataTable实例,或者设置为您自己的类以获取Books列表

假设您有一个定义为

的图书的类
Public Class Book

    Public Property ID As Integer
    Public Property Title As String 
    Public Property Code As String
End Class

现在你的组合框可以用这种方式绑定

' Initialize your data -> (or load from db a DataTable)
Dim bks = New List(Of Book)()
Dim b = New Book() With {.Code = "123", .Title = "ABC", .ID = 1}
bks.Add(b)
b = New Book() With {.Code = "456", .Title = "DEF", .ID = 2}
bks.Add(b)

' Create and initialize the BindingSource instance
Dim bs = New BindingSource()
bs.DataSource = bks

' Set the first combo to display the Title
cbo1.ValueMember = "ID"
cbo1.DisplayMember = "Title"
cbo1.DataSource = bs

' Set the second combo to display the code
cbo2.ValueMember = "ID"
cbo2.DisplayMember = "Code"
cbo2.DataSource = bs

现在两个组合框是同步的并且都显示相同的项目,因为在SelectedIndexChange事件中,BindingSource将它们保存在同一记录上

此示例简单地使用自定义类。如果要使用DataTable,请将DataTable设置为BindingSource的DataSource,并将两个组合的DisplayMemberValueMember属性更改为表的列名。

答案 2 :(得分:0)

这可能有效:

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
    Select Case ComboBox1.Text
        Case "Book_Name"
            ComboBox2.Text = "Book Code: 1982637"
        Case "Something On ComboBox1"
            ComboBox2.Text = "Something On ComboBox2"
            'Etc.
    End Select
End Sub