Home > other >  controls linked together in FlowLayoutPanel
controls linked together in FlowLayoutPanel

Time:08-22

I have a form that upon pressing a button creates a panel inside a FlowLayoutPanel. the panel does contain other control objects as can be seen from the pic. The problem that controls in different panels are linked together ,when in choose in combobox all others change to the same

This before any selection

1

After selection :

2

Shouldn't they be bound by their parent control which in this case will be the panel ?

CodePudding user response:

I just tested what happens when you bind two ComboBox controls to the same DataTable directly and when you bind two ComboBox controls to different BindingSources that are bound to the same DataTable. I added four ComboBoxes and two BindingSources to a form and then added this code:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim table1 As New DataTable
    Dim table2 As New DataTable

    With table1.Columns
        .Add("Id", GetType(Integer))
        .Add("Name", GetType(String))
    End With

    With table2.Columns
        .Add("Id", GetType(Integer))
        .Add("Name", GetType(String))
    End With

    With table1.Rows
        .Add(1, "One")
        .Add(2, "Two")
    End With

    With table2.Rows
        .Add(1, "First")
        .Add(2, "Second")
    End With

    BindingSource1.DataSource = table1
    BindingSource2.DataSource = table1

    With ComboBox1
        .DisplayMember = "Name"
        .ValueMember = "Id"
        .DataSource = BindingSource1
    End With

    With ComboBox2
        .DisplayMember = "Name"
        .ValueMember = "Id"
        .DataSource = BindingSource2
    End With

    With ComboBox3
        .DisplayMember = "Name"
        .ValueMember = "Id"
        .DataSource = table2
    End With

    With ComboBox4
        .DisplayMember = "Name"
        .ValueMember = "Id"
        .DataSource = table2
    End With
End Sub

When I ran the project, I saw "One" displayed in the first two ComboBoxes and "First" displayed in the last two, as expected. I was able to make a selection in either of the first two ComboBoxes without affecting the other, while making a selection in either of the last two ComboBoxes did affect the other. This is almost certainly a demonstration of the issue you're seeing and the solution to said issue. Using the same original data source is fine but you should pretty much always use a BindingSource to bind to your control(s).

If you create a user control, as I recommend you do for groups of child controls that you want to reuse, then the BindingSource object(s) can be added in the designer and used internally. You can just add a property to the control for the data source.

  • Related