Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Forms - ErrorProvider + DataGridView

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

like image 441
Ronnie Overby Avatar asked Apr 27 '09 17:04

Ronnie Overby


People also ask

What is the purpose of the ErrorProvider component in C#?

NET Windows Forms ErrorProvider component is used to validate user input on form controls. If a control failed validation, ErrorProvider displays an error icon next to the control and pops up a tooltip with an error message on hovering over the icon.

What is error provider?

ErrorProvider presents a simple mechanism for indicating to the end user that a control on a form has an error associated with it. If an error description string is specified for the control, an icon appears next to the control.


2 Answers

I'm not sure that you can use the ErrorProvider in this manner, however the DataGridView has functionality built into it that's basically the same idea.

The idea is simple. A DataGridViewCell has an ErrorText property. What you do is, you handle the OnCellValidating event and if fails validation, you set the error text property, and you get that red error icon to show up in the cell. Here's some pseudo code:

public Form1()
{
    this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
}

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (!this.Validates(e.FormattedValue)) //run some custom validation on the value in that cell
            {
                this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Error";
                e.Cancel = true; //will prevent user from leaving cell, may not be the greatest idea, you can decide that yourself.
            }
        }
like image 73
BFree Avatar answered Oct 08 '22 17:10

BFree


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();
}
like image 39
Dada Nada Avatar answered Oct 08 '22 17:10

Dada Nada