【问题标题】:WinForms DataGridView behaviour similar to SQL Server Management StudioWinForms DataGridView 行为类似于 SQL Server Management Studio
【发布时间】:2012-01-05 11:45:10
【问题描述】:

我在一个 Windows 窗体项目中使用 DataGridViews。 我想获得类似于 MS SQL Server Management Studio 中编辑模式下出现的内容。

我试着解释一下:我的数据网格中有一些强制 列,我希望只有在这些列中的值有效时才将一行添加到网格中。 如果单元格的值无效,我想通过消息框警告用户并按 ESC,应重置不正确的行。

我尝试使用CellValidatingRowValidating 事件,但我对结果不满意。

你能帮帮我吗?

更新

我是这样实现RowValidating的:

private void myGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
    if (string.IsNullOrEmpty(myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].FormattedValue.ToString()))
    {
        e.Cancel = true;
        myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = "Mandatory";
        MessageBox.Show("Error message");
    }
    else
    {
        myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = string.Empty;
    }
}

当必填字段中的值无效时,会显示消息框并且单元格是红点,但按ESC 我会得到IndexOutOfRangeException。 .. 仅当我显示消息框并对其进行注释该方法有效时才会引发异常(但这不是我想要实现的行为...)

【问题讨论】:

  • 代码在哪里,为什么它不让你满意?
  • @V4Vendetta 我添加了一些代码 :)

标签: c# .net winforms validation datagridview


【解决方案1】:

以下 MSDN 论坛帖子中解释了此问题: DataGridView + RowValidating = Index 4 does not have a value?

基本上,它似乎是 DataGridView 处理验证方式的一个错误(或至少是非常意外的行为) - MessageBox.Show() 导致对不再存在的行进行验证。

我发现对您的代码进行以下更改可以解决问题:

private void myGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e) 
{ 
    // Note the check to see if the current row is dirty
    if (string.IsNullOrEmpty(myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].FormattedValue.ToString()) &&  myGrid.IsCurrentRowDirty) 
    { 
        e.Cancel = true; 
        myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = "Mandatory"; 
        MessageBox.Show("Error message"); 
    } 
    else 
    { 
        myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = string.Empty; 
    } 
} 

更改是检查正在验证的行是否脏 - 当您按 Escape 并删除一行时,它不再脏,这样可以防止错误地尝试对其进行编辑。

【讨论】:

  • 感谢您的宝贵建议,它非常有效!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多