SelectedIndexChanged事件也会触发错误的datagridviewcomboboxcell

时间:2015-02-10 04:46:34

标签: c# datagridview selectedindexchanged datagridviewcomboboxcell

我有一个datagridview,里面有2个datagridviewcomboboxcolumns。我通过editingcontrolshowing方法设置selectedindexchanged方法(因为这是我读它应该怎么做?) 但是,出于某种原因,当第一次更改为第二个组合框时,此事件将触发。

我的问题是;是什么导致这种方法开火?我明确地检查它是在分配处理程序之前的第一列,但是我仍然需要检查处理程序本身,因为至少在一次出现时columnindex是1。

非常感谢任何帮助。如果我对任何事情都不清楚,请告诉我。

private void AddLicenses_Load(object sender, EventArgs e)
{
    this._data = this.GetData();

    DataGridViewComboBoxColumn productColumn = new DataGridViewComboBoxColumn();
    productColumn.DataPropertyName = "Name";
    productColumn.HeaderText = "Product";
    productColumn.Width = 120;
    productColumn.DataSource = this._data.Select(p => p.Name).Distinct().ToList();
    this.licenses.Columns.Add(productColumn);

    DataGridViewComboBoxColumn distributorColumn = new DataGridViewComboBoxColumn();
    distributorColumn.DataPropertyName = "Distributor";
    distributorColumn.HeaderText = "Distributor";
    distributorColumn.Width = 120;
    this.licenses.Columns.Add(distributorColumn);
}

private void licenses_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox productDropDown = (ComboBox)e.Control;

    if (productDropDown != null && this.licenses.CurrentCell.ColumnIndex == 0)
    {
        productDropDown.SelectedIndexChanged -= productDropDown_SelectedIndexChanged;
        productDropDown.SelectedIndexChanged += productDropDown_SelectedIndexChanged;
    }
}

private void productDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
    if (this.licenses.CurrentCell.ColumnIndex == 0)
    {
        ComboBox productDropDown = (ComboBox)sender;

        DataGridViewComboBoxCell distributorCell = (DataGridViewComboBoxCell)this.licenses.CurrentRow.Cells[1];
        distributorCell.Value = null;
        distributorCell.DataSource = this._data.Where(p => p.Name == (string)productDropDown.SelectedValue).OrderBy(p => p.UnitPrice).Select(d => new EnLicense() { Distributor = d.Distributor, UnitPrice = d.UnitPrice }).ToList();
        distributorCell.ValueMember = "Distributor";
        distributorCell.DisplayMember = "DistributorDisplay";
    }
}

1 个答案:

答案 0 :(得分:0)

这是预期的,因为编辑控件类型被缓存,如果类型相同,则重用控件。在您的情况下,同一个ComboBox控件将在DataGridViewComboBoxColumn中重复使用。这是为了第二次DataGridViewComboBoxColumn被解雇了。

有关更多详细信息,请参阅此MSDN链接中的 Do ComboBox控件是否可以跨列重用,或者每列是否都有自己的ComboBox编辑控件?问题。