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?
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.
try this
listBox1.DataSource = bindingSource1;
listBox2.DataSource = bindingSource2;
...
private void button1_Click(object sender, EventArgs e)
{
listBox2.DataSource = listBox1.DataSource;
}
Ok, solved it. I have to manipulate the underlying collection and then reset bindings at the end. Now it's almost instantly moving :)
精彩评论