我如何将ErrorProvider与DataGridView控件上的单个单元格挂钩?
我如何将ErrorProvider与DataGridView控件上的单个单元格挂钩?
我对BFree的解决方案有问题,因为在单元格处于编辑模式时没有任何显示,但是如果我结束编辑,就会出现数据格式错误(因为我的值是double)。我通过直接将ErrorProvider附加到单元格编辑控件上来解决这个问题,代码如下:
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();
}
我不确定您是否可以以这种方式使用ErrorProvider,但是DataGridView内置了基本相同的功能。
思路很简单。 DataGridViewCell具有ErrorText属性。您所要做的就是处理OnCellValidating事件,如果验证失败,则设置错误文本属性,并使该红色错误图标出现在单元格中。以下是一些伪代码:
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.
}
}
Form
/UserControl
的属性AutoValidate
设置为EnableAllowFocusChange
,而不是不设置Cancel
。这样即使取消验证,也允许你更改焦点。 - Robert S.您可以将 IDataErrorInfo
实现到您的 BusinessObjects 中,并将 BindingSource 设置为 ErrorProvider 的 DataSource。这样,您的 BusinessObject 内部验证将显示在 DataGrid 中,并自动绑定到所有字段上。
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;
}