josecortesp
josecortesp

Reputation: 1576

DatagridView: on every "onmouseenter" on any cell, the cellFormatting event is raised?

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:

  1. The e.value is set with the right value, but it doesn't persist
  2. And the event is raised like a millions of time, and sometimes ran into a SO exception.

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

Answers (1)

Jacob Seleznev
Jacob Seleznev

Reputation: 8141

You can try to handle CurrentCellDirtyStateChanged and check for IsCurrentCellDirty property. If it's true - validate input.

Upvotes: 1

Related Questions