Windows窗体 - ErrorProvider + DataGridView

Ron*_*rby 8 .net c# datagridview errorprovider winforms

如何在DataGridView控件上使用单个单元格挂接ErrorProvider?

小智 7

我在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();
}
Run Code Online (Sandbox Code Playgroud)


BFr*_*ree 5

我不确定您是否可以以这种方式使用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.
            }
        }
Run Code Online (Sandbox Code Playgroud)