使用BindingSource非常慢?

时间:2010-12-24 09:25:37

标签: .net winforms listbox bindingsource

我有一个C#Windows Forms项目,其中包含一个包含2个ListBox和一个按钮的Form。 在FormLoad上,左侧ListBox包含一个列表(大约1800个项目),其中包含有关证券(ID和名称)的信息,当用户点击该按钮时,所有证券都从左侧列表框移动到右侧。

当我没有使用BindingSources时,即我直接使用ListBoxes的Items属性时,移动过程需要几秒钟:

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);
    }
}

但是,当我使用BindingSources时需要几分钟时间:

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);
    }
}

BindingSource方式需要更长时间的原因是什么? 有没有办法让它更快?

3 个答案:

答案 0 :(得分:6)

在对BindingSource进行大量更改之前,应该取消设置BindingSource上的RaiseListChangedEvents属性,如果完成后重置,则应该重置。然后,您可以使用ResetBindings刷新绑定控件。

您还应该使用BeginUpdate / EndUpdate在列表框项目上包装大量操作,以避免重绘。这可能是造成经济放缓的主要因素。

答案 1 :(得分:0)

试试这个

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

...

private void button1_Click(object sender, EventArgs e)
{
      listBox2.DataSource = listBox1.DataSource;
}

答案 2 :(得分:0)

好的,解决了。 我必须操纵底层集合,然后在最后重置绑定。现在它几乎立即移动:))

相关问题