4

I have a C# Windows Forms project with a Form containing 2 ListBoxes and a button. On FormLoad the left ListBox is filled with a list (about 1800 items) containing information about Securities (ID and Name) and when the user clicks on the button all the securities are moved from the left listbox to the right.

When I'm not using BindingSources, i.e. I'm directly using the Items property of the ListBoxes the moving process takes a few seconds:

private void button1_Click(object sender, EventArgs e)
{
    while (listBox1.Items.Count > 0)
    {
         Security s = listBox1.Items[0] as Security;
         listBox1.Items.Remove(s);
         listBox2.Items.Add(s);
    }
}

But, when I'm using BindingSources it takes several minutes:

listBox1.DataSource = bindingSource1;
listBox2.DataSource = bindingSource2;

...

private void MainForm_Load(object sender, EventArgs e)
{
    ICollection<Security> securities = GetSecurities();
    bindingSource1.DataSouce = securities;
}

private void button1_Click(object sender, EventArgs e)
{
    while (bindingSource1.Count > 0)
    {
        bindingSource1.Remove(s);
        bindingSource2.Add(s);
    }
}

What's the reason for the BindingSource-way to take so much longer? Is there any way to make it faster?

nogola
  • 214
  • 4
  • 12

3 Answers3

7

You should unset the RaiseListChangedEvents property on the BindingSource before you do a big set of changes on the BindingSource and reset if after you're done. Then you can use ResetBindings to refresh the bound controls.

You should also wrap large sets of operations on listbox items with a BeginUpdate/EndUpdate to avoid redrawing. This is likely what's causing the most of the slowdown.

Alex J
  • 9,905
  • 6
  • 36
  • 46
0

try this

listBox1.DataSource = bindingSource1;
listBox2.DataSource = bindingSource2;

...

private void button1_Click(object sender, EventArgs e)
{
      listBox2.DataSource = listBox1.DataSource;
}
Binil
  • 6,445
  • 3
  • 30
  • 40
  • No can do... I simplified my problem for this example, but I have to move only those securities the user selects. The problem is when the user selects many of them... – nogola Dec 24 '10 at 09:53
0

Ok, solved it. I have to manipulate the underlying collection and then reset bindings at the end. Now it's almost instantly moving :)

nogola
  • 214
  • 4
  • 12