【问题标题】:Cannot edit DataGridView-cell, Validating-event sets e.Cancel = true无法编辑 DataGridView 单元格,验证事件集 e.Cancel = true
【发布时间】:2015-02-24 12:20:03
【问题描述】:

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。用户无法编辑此无效值。

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

【问题讨论】:

    标签: c# .net winforms datagridview


    【解决方案1】:

    如果您只想在用户更改值时进行验证,是否可以在应用验证之前检查修改?比如:

    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 !!!!
        }
    }
    

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

    【讨论】:

    • 谢谢,这是一个适用于我的好主意。但是,我仍然对始终有效的不同方法感兴趣。
    • 是的,同意。虽然我猜如果底层数据验证失败,必须有一种方法告诉验证处理程序忽略单元格
    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 2011-02-08
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多