【问题标题】:Calling DataGridView's Rows.Clear() more than one time throws exception多次调用 DataGridView 的 Rows.Clear() 会抛出异常
【发布时间】:2014-10-16 09:25:04
【问题描述】:

我遇到了这个问题。

我在C# 中实现了一个自定义类,扩展了System.Windows.Forms.DataGridView。 我需要以编程方式重建Rows 列表,清除它并再次添加行(我没有使用BindingSource/Databases 或类似的东西,我也不需要这些)。

问题是:当我第一次调用我的方法Rearrange() 时,下一次我在this.Rows.Clear() 行中得到Exception(对不起,我的系统是意大利语):

System.Windows.Forms.dll 中的 Eccezione non gestita di tipo 'System.InvalidOperationException'

Ulteriori information: Operazione non riuscita。 Impossibile eseguire il commit o l'annullamento della modifica al valore della cella。

这是我写CustomDataGridView方法Rearrange()的方法:

public void Rearrange()
{
    List<Alarm> list = alarms.GetAllarms();

    this.Rows.Clear();

    if (list.Count > 0)
    {
        DateTime lastdate = list[0].date;
        Rows.Add(new DataGridMarker(lastdate));
        Rows.Add(new DataGridMarker(lastdate));

        foreach (Alarm alarm in list)
        {
            if (lastdate < alarm.data)
            {
                lastdate = alarm.data;
                this.Rows.Add(new DataGridMarker(lastdate));
            }
            this.Rows.Add(new CustomDataGridViewRow(alarm.type, new object[] {
                alarm.superCode + "-" + alarm.code,
                alarm.time.ToString(@"hh\:mm"),
                alarm.description,
                alarm.details
            }));
        }
    }
}

我无法理解我做错了什么...我已将我的 datagridview 以及所有列、行和单元格设置为只读我不知道为什么它应该进行一些编辑。

你能帮我解决这个问题吗?

非常感谢:3

【问题讨论】:

  • 你能告诉哪行代码抛出了InvalidOperationException吗?
  • 对不起,我认为它很清楚(已编辑)。我试图解释this.Rows.Clear() 抛出异常(见标题),这种行为很奇怪:(
  • 你能在该行设置调试器并查看第二次 Rows 是否为空吗?
  • 不,它不为空,我已经检查过了。

标签: c# .net windows winforms datagridview


【解决方案1】:

检查您的 datagridview 是否未处于编辑模式。在 rows.clear 之前添加以下行对我有用

datagridview1.EndEdit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多