I have a validation issue that I am having trouble with and would
appreciate any insight into the issue.
I'll try to make the description as simple as possible.
Say I have a datagridview with 3 columns. From a data entry
perspective, I need my users to enter values into the 3 columns
starting from left to right.
In this scenario, the user clicks on a new row, but they click on the
third column instead of the first. They enter a value in the third
column and in my CellValidating event I notice that the first column
is empty. Is set e.cancel = true and force navigation to the first
column, however, the validating event for the currentcell continues to
fire and I get stuck in a sort of endless loop. Here is the code
private void gvLineItems_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (gvLineItems.Columns[e.ColumnIndex].Name.ToUpper() == "LI_GL")
{
if
(string.IsNullOrEmpty(gvLineItems.Rows[e.RowIndex].Cells["LI_STOCK"].Value.ToString()));
{
MessageBox.Show("Please enter a stock
number first.", "Stock number required", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
gvLineItems.Rows[e.RowIndex].Cells["LI_STOCK"].Selected = true;
gvLineItems.CurrentCell =
gvLineItems.Rows[e.RowIndex].Cells["LI_STOCK"];
e.Cancel = true;
return;
}
}
}
Any ideas or suggestions on the best practices for this kind of data
validation?
Thanks in advance.
ClayB - 20 Feb 2007 16:06 GMT
You can probably avoid your loop problem by setting a flag and only do
the validation when you are not trying to explicitly move to the empty
cell.
bool inValidateMove = false;
void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (!inValidateMove && e.ColumnIndex != 0 &&
(dataGridView1[0, e.RowIndex].Value == null
|| dataGridView1[0,
e.RowIndex].Value.ToString().Length == 0))
{
MessageBox.Show("Must enter col 0");
e.Cancel = true;
inValidateMove = true;
dataGridView1.CurrentCell = dataGridView1[0,
e.RowIndex];
inValidateMove = false;
}
}
======================
Clay Burch
Syncfusion, Inc.
Spottswoode - 21 Feb 2007 22:56 GMT
Thank you Clay.
I am using a flag like you mentioned and the validation is going very
smoothly now.
> You can probably avoid your loop problem by setting a flag and only do
> the validation when you are not trying to explicitly move to the empty
[quoted text clipped - 21 lines]
> Clay Burch
> Syncfusion, Inc.