I have a windows form application which contains a datgridview. I need to enforce cell validations on the datagridview cells so that it does not accept negative values. I found a suitable code for it from the msdn library.
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int newInteger;
// Don't try to validate the 'new row' until finished
// editing since there
// is not any point in validating its initial value.
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
if (!int.TryParse(e.FormattedValue.ToString(),
out newInteger) || newInteger < 0)
{
e.Cancel = true;
dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer";
}
}
Unfortunately the code only allows integers to be entered in the datagridview. Since i have a column name as "Item Name" which is supposed to be entered as text there is an issue in the code. It generates an error message when i type in the name of the item.The rest of the cell validations are perfectly working! How am i supposed to edit the code so that it does not generate this error?
Thanks in advance
Mirfath
DataGridViewCellValidatingEventArgs
e
has a .ColumnIndex
property which you can check to make sure validation is only done on the column you wish.
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e) {
if (e.ColumnIndex == dataGridView1.Columns["MyNumericColumnName"].Index) {
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int newInteger;
// Don't try to validate the 'new row' until finished
// editing since there
// is not any point in validating its initial value.
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
if (!int.TryParse(e.FormattedValue.ToString(),
out newInteger) || newInteger < 0)
{
e.Cancel = true;
dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer";
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With