Windows表单 - 错误提供程序 + 数据网格视图

10

我如何将ErrorProvider与DataGridView控件上的单个单元格挂钩?

5个回答

10

我对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();
}

@Dada-Nada提出的解决方案是可行的! - DrMarbuse

8

我不确定您是否可以以这种方式使用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.
            }
        }

1
我尝试设置ErrorText属性,但在运行时没有任何反应! - Ronnie Overby
很奇怪,它应该可以工作...只需确保您的ErrorText不是空字符串,因为这会删除错误。 - Meta-Knight
1
它应该可以工作,我刚测试过了。我能想到的唯一可能是DataGridView本身有一个ShowCellErrors属性。确保它没有被设置为false。 - BFree
1
@RonnieOverby,你应该将容器Form/UserControl的属性AutoValidate设置为EnableAllowFocusChange,而不是不设置Cancel。这样即使取消验证,也允许你更改焦点。 - Robert S.
1
这篇其他的文章(https://dev59.com/uVzUa4cB1Zd3GeqPzhS5)对我在单元格验证时非常有帮助,当 ErrorText 并不像应该那样容易使用。 - Greg Barth
显示剩余2条评论

3

您可以将 IDataErrorInfo 实现到您的 BusinessObjects 中,并将 BindingSource 设置为 ErrorProvider 的 DataSource。这样,您的 BusinessObject 内部验证将显示在 DataGrid 中,并自动绑定到所有字段上。


1
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;
}

0
你可以向dataGridView.Columns添加一列(例如DataGridViewTextBoxColumn),并将CellTemplate设置为您自己的实现(比如继承自DataGridViewTextBoxCell)。然后在您的实现中,按照您的喜好处理验证、渲染和定位编辑面板以适应您的需求。
您可以在http://msdn.microsoft.com/en-us/library/aa730881(VS.80).aspx上查看示例。
但是,也许还有更简单的解决方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接