"Cannot set Column '<column name>' to be null. Please use DBNull instead." - this is the exception which can be thrown when changing DataGridView combobox to a Default Value (blank or null) or deleting the selected value. It took me a while to fix the problem. I'd like to summarise the three steps I used to create an editable databinding ComboBox in DataGridView:
1 In DataGridView.EditingControlShowing, set ComboBox.DropDownStyle = ComboBoxStyle.DropDown for the desired column(s).
Code: private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
{
DataGridViewComboBoxEditingControl combo = e.Control as DataGridViewComboBoxEditingControl;
combo.DropDownStyle = ComboBoxStyle.DropDown;
combo.TextChanged += new EventHandler(combo_TextChanged);
}
}
Since there is no property to enable this for a DataGridView ComboBox, you need to do this. Here the ComboBox's TextChanged event handler is optional. With it, your application can listen to the ComboBox's TextChanged event and then call the DataGridView's NotifyCurrentCellDirty method so that the DataGridView ends the edit mode after you leave the cell or the new row gets added the moment the you type in the new value. See step 2.
2 Set DataGridView.NotifyCurrentCellDirty(True) in DataGridView.EditingControlShowing or combo_TextChanged
Code: void combo _TextChanged(object sender, EventArgs e)
{
this.dataGridView1.NotifyCurrentCellDirty(true);
}
Without this, the DataGridView stays in an edit mode even after you leave the cell. Without this, no new row will be added when you edit the ComboBox cell. This is a different behaviour from other cell types.
3. The solution is to subscribe to the column changing event for the DataTable bound.
Code: DataTable dataTable = ...;
dataTable.ColumnChanging += new DataColumnChangeEventHandler(dataTable_ColumnChanging);
Code: void dataTable_ColumnChanging(object sender, DataColumnChangeEventArgs e)
{
if (e.Column == dataTable.Columns["myColumn"])
{
if (e.ProposedValue == null)
{
e.ProposedValue = DBNull.Value;
}
}
}
For non-databound editable ComboBox, visit
How to allow a user to type a new value into a DataGridView ComboBox.
For more tips on DataGridView, please visit
http://msdn.microsoft.com/en-au/magazine/cc163669.aspx.