0

I have form with a ListBox and ComboBox

scr1

Both are filled with values using their .DataSource property from the same array

public partial class Form1 : Form
{
    static readonly Random rng = new Random();
    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        int[] list = Enumerable.Range(0, 20).Select((i) => rng.Next(501)).ToArray();

        listBox1.DataSource = list;

        comboBox1.DataSource = list;
    }
}

No other code is added to my form. But when I run the form and select an item from the ListBox, the ComboBox also gets the same item selected. This works vice-versa also.

scr2

How is this black magic happening? How is the ComboBox receiving events or updates to the data binding when the ListBox is manipulated from the UI?

John Alexiou
  • 28,472
  • 11
  • 77
  • 133
  • 1
    As I pointed out in [this post](https://stackoverflow.com/a/35865838/3110834): Since you are binding all combo boxes to the same data source (a single list), they are using a single BindingManagerBase. So when you choose an item from one of combo boxes, the current Position of the shared binding manager base changes and all combo boxes goes to that position of their shared data source. – Reza Aghaei Oct 06 '22 at 19:56
  • @RezaAghaei - is the `BindingManagerBase` stored in the Form and thus shared by all controls that are assigned the same `DataSource` object? – John Alexiou Oct 06 '22 at 20:00
  • Yes, they share a [BindingContext](https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/ContainerControl.cs,0debdf2c88d1d0b7), so when you set DataSource of ComboBox and ListBox to the same list, it basically is stored in the [BindingContext](https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/ListControl.cs,772). So when the selected item of one changes, it basically changes the position of the same currencymanager which results in changing the selected item of the other one. – Reza Aghaei Oct 06 '22 at 20:14

0 Answers0