1

所以,我有一个绑定到 BindingList 的列表框 GUI 元素。我遇到的问题是,每当我将一个项目添加到 BindingList 时,列表框中的相应项目就会被选中。这很重要,因为它会触发列表框中的 SelectedIndexChanged 事件,该事件被设置为资源密集型。

如何删除此默认行为?

编辑:这是我正在使用的代码

BindingList<KeyValuePair<int, string>> savedGLs;
public Form1()
{
    InitializeComponent();
    savedGLs = new BindingList<KeyValuePair<int, string>>();
    lstGLs.DataSource = savedGLs;//lstGLs is my listbox
    lstGLs.DisplayMember = "Value";
    lstGLs.ValueMember = "Key";
    populateMgmtCos();
    populateSavedGLs();//this is where the SelectedIndexChanged event is firing
}
private void populateSavedGLs()
{
    savedGLs.Clear();
    string errmsg = string.Empty;
    using (SqlConnection sqlConn = new SqlConnection(getConnString(true)))
    {
        string sCmd = " SELECT Name, Hmy FROM GLTable";
        DataTable dt = MySqlHelper.ExecuteForDataTable(sqlConn, sCmd, out errmsg);
        foreach (DataRow dr in dt.Rows)
            savedGLs.Add(new KeyValuePair<int,string>(int.Parse(dr["Hmy"].ToString()), dr["Name"].ToString().Trim()));
     }
}

EDIT2:可能是因为我使用的是 3.5 框架吗?我刚刚创建了一个新项目,其中几乎没有任何内容,除了复制我的问题的代码。BindingList 的 Add() 方法似乎在我的列表框上调用 SelectedIndexChanged 方法,添加第一项时调用两次,之后每次调用一次。这是该新项目的完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        BindingList<KeyValuePair<int, string>> bl;
        public Form1()
        {
            InitializeComponent();
            bl = new BindingList<KeyValuePair<int, string>>();
            listBox1.DataSource = bl;
            bl.Add(new KeyValuePair<int, string>(1, "blah1"));
            bl.Add(new KeyValuePair<int, string>(2, "blah2"));
            bl.Add(new KeyValuePair<int, string>(3, "blah3"));
            bl.Add(new KeyValuePair<int, string>(4, "blah4"));
            bl.Add(new KeyValuePair<int, string>(5, "blah5"));
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Console.WriteLine("blah");
        }
    }
}
output:
blah
blah
blah
blah
blah
blah
4

1 回答 1

2

最后,可重现。

不要在构造函数期间将这些项目添加到 BindingList。

快速修复是覆盖表单的 OnLoad 方法:

protected override void OnLoad(EventArgs e) {
  bl.Add(new KeyValuePair<int, string>(1, "blah1"));
  bl.Add(new KeyValuePair<int, string>(2, "blah2"));
  bl.Add(new KeyValuePair<int, string>(3, "blah3"));
  bl.Add(new KeyValuePair<int, string>(4, "blah4"));
  bl.Add(new KeyValuePair<int, string>(5, "blah5"));
  base.OnLoad(e);
}

或从您的生产代码:

public Form1()
{
  InitializeComponent();
  savedGLs = new BindingList<KeyValuePair<int, string>>();
  lstGLs.DisplayMember = "Value";
  lstGLs.ValueMember = "Key";
  lstGLs.DataSource = savedGLs;
}

protected override void OnLoad(EventArgs e) {
  populateMgmtCos();
  populateSavedGLs();
}
于 2012-07-25T18:38:50.880 回答