1

I have a datagridview which has 2 datagridviewcomboboxcolumns in it. I set the selectedindexchanged method via the editingcontrolshowing method (as this is how i've read it is supposed to be done?) However, for some reason, this event fires when first changing to the 2nd combobox.

My question is; what is causing this method to fire? I'm explicitly checking that it is the first column before assigning the handler, but I still need to check in the handler itself, as on at least one occurrence the columnindex is 1.

Any help would be greatly appreciated. Let me know if i'm unclear in anything.

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";
    }
}
Luke
  • 288
  • 2
  • 16

1 Answers1

0

This is expected as the editing control type is cached and if the types are the same, then the control is reused. In your case the same ComboBox control is reused in both the DataGridViewComboBoxColumn. Thatswhy it is fired for the second DataGridViewComboBoxColumn.

See the Do ComboBox controls get reused across columns, or does each column get its own ComboBox editing control? question in this MSDN link for further details.

Junaith
  • 3,298
  • 24
  • 34