Adding values to the DataGridViewComboBoxCell at runtime

Welcome to hackville population me.

The DataGridViewComboBoxCell won’t allow values to be entered in the cell if they are not in the Items collection. Since I can’t modify the Items collection if the DataSource property is set, I add value of the cell that’s causing the DataError to the DataSource for the combo box. Since it doesn’t throw anything sensible like a ComboBoxValueNotInItems exception, and it doesn’t raise something nice like a “DataBinding” event or an “ValueNotInItems” event, or even an “Validating” event, I have to trap the System.ArgumentException. This may come back to bite me later. For one thing, will I ALWAYS set the Datasource to a DataTable object? What if I use another object for the data source.

        private void dgStuff_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
 
            if (e.Exception is System.ArgumentException)
            {
                if (this.dgStuff.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewComboBoxCell)
                {
                    DataGridViewComboBoxCell _cell = this.dgStuffDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewComboBoxCell;
                    DataTable _dt = _cell.DataSource as DataTable;
                    DataRow _newRow = _dt.NewRow();
                    _newRow["LkpCode"] = _cell.Value;
                    _newRow["LkpDescription"] = _cell.Value;
                    _dt.Rows.Add(_newRow);
                    _dt.AcceptChanges();
                }
            }
        }

I found a post in the MSDN forums where they talk about accepting user input in the DataGridViewComboBoxCell which isn’t in the cells Items collection.