How can I hook in the ErrorProvider with individual cells on the DataGridView control?
You could add a column (like DataGridViewTextBoxColumn) to dataGridView.Columns that has the CellTemplate set to your own implementation (say, inherited from DataGridViewTextBoxCell). Then in your implementation - handle validation as you like - rendering and positioning of the editing panel to fit your needs.
You can check a sample at http://msdn.microsoft.com/en-us/library/aa730881(VS.80).aspx.
But then again - there might be a simpler solution.
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.
}
}
private void myGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
var dataGridView = (DataGridView)sender;
var cell = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
if ( ... ) // Validation success
{
cell.ErrorText = string.Empty;
return;
}
dataGridView.EndEdit();
cell.ErrorText = error;
e.Cancel = true;
}
You can just implement IDataErrorInfo
into your BusinessObjects, and set the BindingSource as DataSource for the ErrorProvider too. That way your BusinessObject intern validation shows up in the DataGrid and on all fields the objects are bound to automatically.