Reputation: 33
I have a DataGridView that is sourced from a datatable. I'm trying to stop the user inputting non-numerical or negative integers or doubles into different columns from the datagridview.
I understand that a CellValidating method is commonly used but I can't seem to get it to capture negative values.
private void datagridview1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
string headerText = datagridview1.Columns[e.ColumnIndex].HeaderText;
// Abort validation if cell is not in the Age column.
if (!headerText.Equals("Quantity")) return;
int output;
// Confirm that the cell is an integer.
if (!int.TryParse(e.FormattedValue.ToString(), out output))
{
MessageBox.Show("Quantity must be numeric");
e.Cancel = true;
}
else if (output <= 0)
{
MessageBox.Show("Quantity must not be negative");
e.Cancel = true;
}
}
With the above code, I am still able to get negative or even zero values into the quantity cells.
Help is much appreciated Thanks
Upvotes: 1
Views: 2212
Reputation: 521
I think correct approach would be to make use of ErrorText property.
dataGridView1.Rows[e.RowIndex].ErrorText = "Quantity must not be negative";
This gives clear indication like:
You can also use CellEndEdit event:
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// Clear the row error in case the user presses ESC.
dataGridView1.Rows[e.RowIndex].ErrorText = string.Empty;
}
When Row Headers are not visible:
In that case, validation still works however error message and icon will not get displayed. Use this approach with CellEndEdit even to get more control. This will work even when row headers are not visible.
Upvotes: 1
Reputation: 12459
I think you should place MessageBox
code after Cancel the event.
Because when MessageBox pops up, it loses the focus from Cell
, losing the focus will not let the event Cancel
.
// Confirm that the cell is an integer.
if (!int.TryParse(e.FormattedValue.ToString(), out output))
{
e.Cancel = true;
MessageBox.Show("Quantity must be numeric");
}
else if (output <= 0)
{
e.Cancel = true;
MessageBox.Show("Quantity must not be negative");
}
Upvotes: 1