使用BindingSource很慢?

4
我有一个C# Windows Forms项目,其中包含一个窗体,里面有两个列表框和一个按钮。 在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的原因导致它需要更长时间?有没有办法使它更快?

即使对于1800个项目来说,一秒钟也很长,我无法想象需要几分钟。 - H H
还有:BindingSource 的 DataSource 用于什么? - H H
我已经编辑了帖子,现在你可以看到 DataSource 是一个 ICollection。 - nogola
3个回答

7

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

您还应该使用 BeginUpdate/EndUpdate 将列表框项的大批操作包装起来,以避免重绘。这很可能是造成大部分减速的原因。


0

试一下这个

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

...

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

做不到...我为了这个例子简化了我的问题,但是我必须只移动用户选择的那些证券。问题是当用户选择很多时... - nogola

0

好的,问题解决了。 我必须操作底层集合,然后在最后重置绑定。现在它几乎瞬间移动 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接