I have DataGridView
. In some cells I add some data. If the cell, that I'm currently editing, is empty and I'm about to leave it, a message "bla-bla-bla" is shown to the user and the cell in edition mode must receive the focus back.
For doing this I'm using CellEnter
, CellLeave
, CellEndEdit
etc. and I want cancel those events after checking the value entered in the cell. But Im noob and it doesn't work. Please, help me. Would be glad to see any advice.
Here is a variant of my code. I tried with other events, but it is very naive.
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1[e.ColumnIndex, e.RowIndex] == null)
{
MessageBox.Show("Empty cell!");
dataGridView1.CurrentCell = dataGridView1[e.ColumnIndex, e.RowIndex];
}
}
I think you must look for a solution based on the CellValidating
event of the DataGridView
.
It is fired just when the DataGridView
is about to leave the edition mode and allows you to not accept the value that has been entered by the user. To reject the value entered, in the code of the event-handler, you must set the e.Cancel
to True
.
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (!IsValueValid(e.FormattedValue))
{
e.Cancel = true;
MessageBox.Show("Not Valid!");
}
}
There are many examples in the web, one can be found directly in the documentation of DataGridViewCellValidatingEventArgs
in the MSDN. Take a look also to the documentation of the property DataGridViewCellValidatingEventArgs.FormattedValue
Note that the method IsValueValid(Object o)
is not part of the DataGridView
component, is just a naming example, you should declare it in your code and provide a body for the validation.
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