c# - 无法编辑 DataGridView 单元格,验证事件集 e.Cancel = true

标签 c# .net winforms datagridview

DatagridView 又让我抓狂了。所以我有一个带有 DatagridView 的表单,它一直有效。但是现在数据库中有一个无效值导致 Validating 事件阻止程序流。

就是这样:

private void GrdChargeAssignment_Validating(Object sender, DataGridViewCellValidatingEventArgs e)
{
    e.Cancel = false;
    var grid = (DataGridView)sender;
    ErpService.ArrivalChargeAssignment ass = grid.Rows[e.RowIndex].DataBoundItem as ErpService.ArrivalChargeAssignment;

    string countValue = grid.Rows[e.RowIndex].Cells[AssignedCol.Name].EditedFormattedValue.ToString();
    if (string.IsNullOrWhiteSpace(countValue))
    {
        grid.Rows[e.RowIndex].Cells[AssignedCol.Name].Value = "0";
        countValue = "0";
    }

    int count;
    if (!int.TryParse(countValue, out count))
    {
        grid.Rows[e.RowIndex].ErrorText = "Insert a valid integer for count!";
        e.Cancel = true;
    }
    else if (count > ass.Count_Actual)
    {
        grid.Rows[e.RowIndex].ErrorText = string.Format("Please insert a count between 0 and arrival-count({0})!", ass.Count_Actual);
        e.Cancel = true;  // !!!! HERE !!!!
    }

    if (e.Cancel == false)
        grid.Rows[e.RowIndex].ErrorText = "";
}

我用 注释的那行!!!! HERE !!!! 导致事件被取消,从而阻止了 gui。用户无法编辑此无效值。

在数据绑定(bind)期间,我已经取消订阅此事件以禁用它。但现在如果用户点击单元格编辑无效值,它仍然会被触发。调用堆栈窗口显示它是从 CellMouseDown 事件内部触发的。我怎样才能防止这种情况?我希望它仅在用户编辑单元格并离开时才得到验证。

最佳答案

如果您只想在用户更改值时进行验证,您可以在应用验证之前检查修改吗?像这样的东西:

else if (count > ass.Count_Actual)
{
    if( count == ass.Count )
    {
        // The data has not changed, do not validate
    }
    else
    {
        grid.Rows[e.RowIndex].ErrorText = string.Format("Please insert a count between 0 and arrival-count({0})!", ass.Count_Actual);
        e.Cancel = true;  // !!!! HERE !!!!
    }
}

如果用户将该值编辑为另一个无效值,验证将开始,否则,错误数据将被忽略。

关于c# - 无法编辑 DataGridView 单元格,验证事件集 e.Cancel = true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28695656/

相关文章:

C# MouseLeave 在显示上下文菜单之前触发?

c# - 在数据库列中存储尺寸(连同图像)?

c# - 所有类型的 sql 异常列表

c# - 在 b2c 中的用户注册时触发 azure 函数

c# - 使用 JSON.NET 反序列化字典

c# - 按钮上没有可见文字,但屏幕阅读器需要文字?

c# - 如何使用 SendMessage() 发送鼠标 Action

c# - 将对象转换为方法泛型类型

.net - Log4net 电子邮件整个日志

c# - 如何确保 c# 解决方案中的所有项目都使用相同版本的第三方库?