10

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

4

5 回答 5

10

我对 BFree 的解决方案的问题是,当单元格处于编辑模式时,什么都没有显示,但是如果我结束编辑,我会收到数据格式错误(因为我的值是双精度值)。我通过将 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();
}
于 2013-07-29T16:45:10.717 回答
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.
            }
        }
于 2009-04-27T18:07:57.253 回答
2

您可以只IDataErrorInfo在您的 BusinessObjects 中实现,并将 BindingSource 也设置为 ErrorProvider 的 DataSource。这样,您的 BusinessObject 实习生验证就会显示在 DataGrid 中以及对象自动绑定到的所有字段上。

于 2010-04-01T09:25:17.890 回答
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;
}
于 2009-07-22T18:43:48.257 回答
0

您可以向 dataGridView.Columns 添加一列(如 DataGridViewTextBoxColumn),将 CellTemplate 设置为您自己的实现(例如,从 DataGridViewTextBoxCell 继承)。然后在您的实现中 - 根据需要处理验证 - 渲染和定位编辑面板以满足您的需求。

您可以在http://msdn.microsoft.com/en-us/library/aa730881(VS.80).aspx查看示例。

但话又说回来 - 可能有一个更简单的解决方案。

于 2009-04-27T17:33:36.993 回答