Windows Forms - ErrorProvider + DataGridView

Ronnie Overby picture Ronnie Overby · Apr 27, 2009 · Viewed 18.9k times · Source

How can I hook in the ErrorProvider with individual cells on the DataGridView control?

Answer

Dada Nada picture Dada Nada · Jul 29, 2013

The problem I have with BFree's solution is that nothing shows up while the cell is in edit mode, but if I end edit, I get a data format error (because my value is a double). I solved this by attaching the ErrorProvider directly to the cell edit control like this:

private ErrorProvider ep = new ErrorProvider();
private void DGV_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex < 0 || e.RowIndex < 0)
        return;
    double val;
    Control edit = DGV.EditingControl;
    if (edit != null && ! Double.TryParse(e.FormattedValue.ToString(), out val))
    {
        e.Cancel = true;
        ep.SetError(edit, "Numeric value required");
        ep.SetIconAlignment(edit, ErrorIconAlignment.MiddleLeft);
        ep.SetIconPadding(edit, -20); // icon displays on left side of cell
    }
}

private void DGV_CellEndEdt(object sender, DataGridViewCellEventArgs e)
{
    ep.Clear();
}