绑定下拉框时避免触发SelectedIndexChanged事件

时间:2023-03-04 15:10:32

在从数据库读取数据集绑定到下拉框时会立即触发其SelectedIndexChanged事件造成异常,可对其SelectedIndexChanged事件采取先解除后附加的方法解决。

cmbXl_gt.ValueMember = "id";
            cmbXl_gt.DisplayMember = "名称";

同时绑定两列:一个显示,一个调用

  private void initComobox1()
{
Comobox1.SelectedIndexChanged -= new System.EventHandler(Comobox1_SelectedIndexChanged);
db myDB = new db();
DataTable dt = new DataTable("logoo");
dt = myDB.BindXl();
DataSet ds = new DataSet("gv");
ds.Tables.Add(dt);
Comobox1.DataSource = ds.Tables[];
Comobox1.ValueMember = "id";
Comobox1.DisplayMember = "名称";
initGrid1(Comobox1.SelectedValue.ToString());
Comobox1.SelectedIndexChanged += new System.EventHandler(Comobox1_SelectedIndexChanged);
}