DataGridView ComboBox列选择已更改事件

时间:2012-09-07 18:11:24

标签: c# winforms

我有一个包含2个组合框列的数据网格。我为组合框列编写了选择更改事件,如下所示。

private void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{ 
  ComboBox cb = e.Control as ComboBox;
                if (cb!=null)
                { cb.SelectionChangeCommitted -= new EventHandler(cb_SelectedIndexChanged);

                    // now attach the event handler
                    cb.SelectionChangeCommitted += new EventHandler(cb_SelectedIndexChanged);
                }
}

void cb_SelectedIndexChanged(object sender, EventArgs e)
     {
       var tb = datagrdADDTEMP.EditingControl as ComboBox;
       if (tb != null)
       str = tb.SelectedValue != null ? tb.SelectedValue.ToString() : null;
                     Assesment_Business_layer.Businesslayer bl = new Assesment_Business_layer.Businesslayer();
                     DataSet ds = new DataSet();**strong text**
                     ds = bl.GetSubCatNamesBA(str);
                     cmbDataGridSubCategory.DataSource = ds.Tables[0];
                     cmbDataGridSubCategory.DisplayMember = "SubCategoryName";
                     cmbDataGridSubCategory.ValueMember = "SubCategoryCode";
                 }
     }

它与第一个组合框列合作良好,但问题是当我从第二个组合框列中选择项目时,上面的选择更改事件也会提高..但我不想为第二个组合提出选择更改事件柱。它应仅针对第一个组合框提升。

请帮助我解决这个问题。

1 个答案:

答案 0 :(得分:2)

问题似乎是你要将事件处理程序添加到任何组合框中,无论它是什么列都是无关紧要的,所以你必须先找到触发事件的列,为此你必须看一下Grid_EditingControlShowing事件处理程序的发送方对象(它是一个DataGridView)及其CurrentCell,SelectedColumns或SelectedCells属性。

示例:

private void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if(((DataGridView)sender).CurrentCell.ColumnIndex == 0) //Assuming 0 is the index of the ComboBox Column you want to show
    {
        ComboBox cb = e.Control as ComboBox;
        if (cb!=null)
        {
            cb.SelectionChangeCommitted -= new EventHandler(cb_SelectedIndexChanged);
            // now attach the event handler
            cb.SelectionChangeCommitted += new EventHandler(cb_SelectedIndexChanged);
        }
    }
}

使用SelectedColumns或SelectedCells的示例非常类似,如果您想了解有关该属性的更多信息,可以查看他们的documentation on MSDN