1

我有一个datagridview其中有2个datagridviewcomboboxcolumns。我通过编辑控件展示方法设置了selectedindexchanged方法(因为我已经读过它,应该这样做) 但是,由于某种原因,当第一次更改为第二个组合框时,此事件触发。SelectedIndexChanged事件也发射错误datagridviewcomboboxcell

我的问题是;是什么导致这种方法触发?我明确检查它是分配处理程序之前的第一列,但我仍然需要检查处理程序本身,因为至少在一次出现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"; 
    } 
} 

回答

0

这是因为编辑控件类型被缓存,并且如果类型相同,则控件被重用。在你的情况下,相同的ComboBox控件可以在DataGridViewComboBoxColumn中重复使用。这就是为什么它被解雇的第二个DataGridViewComboBoxColumn

查看ComboBox控件是否在列中被重用,还是每列都有自己的ComboBox编辑控件?问题在这MSDN链接的进一步细节。

相关问题