【问题标题】:Error When Adding Row To DataGridView Inside RowValidated Event在 RowValidated 事件中向 DataGridView 添加行时出错
【发布时间】:2019-01-23 01:12:17
【问题描述】:

我想在验证行后向 datagridview 添加一个新行。我在 RowValidated 事件中调用我的 AddNewRow 方法。但它给出“无法在此事件处理程序中执行操作”错误。

我的datagridview没有绑定任何数据源,并且AllowUsersToAddRow属性设置为false。

DataGridView 只有一列,名为“Cost”。

这是我的代码;

 private void RMaterialDGV_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        DataGridView dgv = sender as DataGridView;
        if (dgv.IsCurrentRowDirty)
        {
            if(dgv.CurrentRow.Cells["Cost"].Value == null || dgv.CurrentRow.Cells["Cost"].Value.ToString().Length == 0
                || dgv.CurrentRow.Cells["Cost"].Value.ToString() == 0.ToString())
            {
                e.Cancel = true;
            }
        }
    }

    private void RMaterialDGV_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView dgv = sender as DataGridView;
        if (dgv.CurrentRow.Index == dgv.Rows.Count - 1 && dgv.CurrentRow.Cells["Cost"].Value != null)
        {
            if (dgv.CurrentRow.Cells["Cost"].Value.ToString().Length > 0)
                AddNewRowToDGV();
        }
    }

    private void AddNewRowToDGV()
    {
        int index = RMaterialDGV.Rows.Add();
        RMaterialDGV.Rows[index].Cells["Cost"].Value = 0;
    }

我使用此方法在(其他项目)之前添加新行,但从未收到这些错误。

我错过了什么?

提前致谢。

【问题讨论】:

  • 哪一行代码出错了?
  • @ChetanRanpariya 感谢您的留言。 AddNewRowToDGV 方法内部给出错误; int index = RMaterialDGV.Rows.Add();
  • @C-PoundGuru 感谢您的留言。但是我几乎检查了互联网上关于这个问题的所有帖子。有重复的问题,但尚未给出有效答案。

标签: c# datagridview


【解决方案1】:

当控件是数据绑定时,不能以编程方式将行添加到 DataGridView 的行集合中。

相反,您可以向数据源添加行。将您的 AddNewRowToDGV 方法更新为如下所示。

  private void AddNewRowToDGV()
        {
            var data = (DataTable) dataGridView1.DataSource;
            var row = data.NewRow();
            row["Cost"] = 1;
            data.Rows.Add(row);    
        }

【讨论】:

  • 您好,感谢您的帮助,但我的 DataGridView 不是我在消息中提到的数据边界。
【解决方案2】:

我解决了这个问题,创建了一个 DataTable 并将这个 DataTable 绑定到我的 DataGridView。但我无法真正理解导致实际问题的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多