Reputation: 1576
I have a Datagridview, on which I need to validate the user input on certain rows, and change it according to it's value. As a example, if the user input a product code that doesn't exist on the DB, a search for a product dialog raises and search for the product and returns the correct code. So after reading around a lot, I decided to handle the CellFormating event: but I ran into two problems:
And that's why I put a mbox in the event handler and now the programs does nothing but shows that mbox.
The point here is, even when the forms is newly created, the event raises a lot, and, every time I move the mouse pointer over any cell, the event is raised again.
What's the best option here? below is the code inside the event handler:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
try
{
if (e.ColumnIndex == 0 && !dataGridView1.Rows[e.RowIndex].IsNewRow)
{
if (!Rep.Cajero_ProductoExiste(double.Parse(e.Value.ToString())))
{
BuscarEIngresarProducto(ref e);
}
}
MessageBox.Show("Event handler raised");
}
catch
{
e.FormattingApplied = false;
}
}
Where Rep.Cajero_ProductoExiste
is a method that returns a bool=true if the product exists, and the method BuscarEIngresarProducto()
is as below:
private void BuscarEIngresarProducto(ref DataGridViewCellFormattingEventArgs e)
{
Busqueda b = new Busqueda(Rep, 2);
if (b.ShowDialog() == DialogResult.OK)
{
e.Value = b.ProductoCodigo;
dataGridView1.CurrentRow.Cells["pk"].Value = b.Producto;
e.FormattingApplied = true;
}
}
Upvotes: 0
Views: 265
Reputation: 8141
You can try to handle CurrentCellDirtyStateChanged and check for IsCurrentCellDirty property. If it's true - validate input.
Upvotes: 1