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/