I am trying to make data grid view cell change its value to default when user enters invalid data. The cell type is int?.
I tried to do it with CellValidating
event, it is possible to give number with DataGridView.EditingControl.Text = "0"
, but ig it is not possible to change cell value to null
. But the column is binded to int? typed property. I also tried to do it with CellParsing
event but this event fires after cell is validated, so if user enters empty value and hits enter, data grid view throws error because cell only takes int values, but I want it to change the value to null if user enters empty value.
private void DataGridView_NumberCellValidate(object sender, DataGridViewCellValidatingEventArgs e){
if (e.ColumnIndex != 8 && e.ColumnIndex != 9) return;
if (!int.TryParse(e.FormattedValue?.ToString(), out int temp)) {
e.Cancel = true;
// i want to not cancel the endEdit, but change value to default if value is not valid
MessageBox.Show("Value is not number.");
}}
1667 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.