How can I hook in the ErrorProvider with individual cells on the DataGridView control?
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.
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.
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.
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With