在C#窗体中绑定Comboboxes

时间:2016-07-08 08:38:12

标签: c# windows forms data-binding combobox

我有2个组合框,它们都使用相同的数据源。 每当我更改其中一个组合框时,另一个更改为完全相同的值。

似乎要解决这个问题,我需要使用数据绑定。

我尝试过很多东西,但似乎没什么用。 我的组合框名为comboBox1和comboBox2。 下面是我试图用来使combobox2独立于comboBox1的源代码。 任何帮助将不胜感激。

    BindingSource bs = new BindingSource(this.claimTypeBindingSource, null);
    BindingContext bc = new BindingContext();
    comboBox2.BindingContext = bc;
    comboBox2.DataSource = bs.DataSource;
    comboBox2.DisplayMember = "ClaimType";

EDIT 我刚刚从comboBox1中获取了dataSource赋值并使用代码进行了分配 - 代码现在看起来像这样。

    private void Form1_Activated(object sender, EventArgs e)
    {
        BindingSource bs1 = new BindingSource(this.claimTypeBindingSource, null);
        BindingContext bc1 = new BindingContext();
        comboBox1.BindingContext = bc1;
        comboBox1.DataSource = bs1.DataSource;
        comboBox1.DisplayMember = "ClaimType";

        BindingSource bs2 = new BindingSource(this.claimTypeBindingSource, null);
        BindingContext bc2 = new BindingContext();
        comboBox2.BindingContext = bc2;
        comboBox2.DataSource = bs2.DataSource;
        comboBox2.DisplayMember = "ClaimType";
    }

这还没有解决问题。 如果我改变1个comboBox,那么另一个也会改变。

2 个答案:

答案 0 :(得分:2)

我刚刚解决了它:-) 这是有效的 - 我已将它放入我的真实项目中并且完美运行。

private void Form1_Activated(object sender, EventArgs e)
    {
        comboBox1.DataSource = new BindingSource(this.claimTypeBindingSource, null);
        comboBox1.DisplayMember = "ClaimType";

        comboBox2.DataSource = new BindingSource(this.claimTypeBindingSource, null);
        comboBox2.DisplayMember = "ClaimType";
    }

答案 1 :(得分:0)

这是我用来填充两个组合框的简单代码 从第一个组合框更改值不会更改其他值的值。

Public Class Form1

    Dim data As New List(Of Product)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim bs1 As New BindingSource(data, Nothing)
        Dim bc1 As New BindingContext()
        ComboBox1.BindingContext = bc1
        ComboBox1.DataSource = bs1.DataSource
        ComboBox1.DisplayMember = "ProductName"

        Dim bs2 As New BindingSource(data, Nothing)
        Dim bc2 As New BindingContext()
        ComboBox2.BindingContext = bc2
        ComboBox2.DataSource = bs2.DataSource
        ComboBox2.DisplayMember = "ProductName"

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        For intCounter As Integer = 1 To 10
            data.Add(New Product(intCounter, intCounter.ToString))
        Next

    End Sub
End Class


Public Class Product

    Public Property ProductID As Integer = 0
    Public Property ProductName As String = String.Empty

    Public Sub New(ID As Integer, Name As String)

        Me.ProductID = ID
        Me.ProductName = Name
    End Sub

End Class