【问题标题】:Deleting Rows (physically) from DataGridView从 DataGridView 中删除行(物理上)
【发布时间】:2012-12-04 09:46:14
【问题描述】:

问题是,当您点击删除时,即使行已从视图中删除,如果您检查 Rows.Count,仍会保留。

同样的情况也发生在DataTables 和 'Delete(DataRow)',我使用 Remove/RemoveAt 跳过了。

所以在我从DataGridView 中删除行后,如果我将DataSource 当作DataTable 并尝试导出它(在本例中为 csv)会抛出一条消息,它无法获取已删除的信息行(释义 - 抱歉,调试器使用母语)。

我可以想出一些棘手的方法来玩弄DataGridViewRowCollection、DataGridViewSelectedRowCollection 和 DataTables,但我真的需要更可靠、更简单的方法。

【问题讨论】:

    标签: c# datagridview delete-row


    【解决方案1】:

    好的,解决方案在 DataRowState 上。 为了摆脱所有手动删除的行,您必须执行以下操作:

    DataTable t = (DataTable)dataGridView1.DataSource;
    
    for (int i = t.Rows.Count - 1; i >= 0; i--)
    {
        if (t.Rows[i].RowState == DataRowState.Deleted)
               t.Rows.RemoveAt(i);
    }
    

    【讨论】:

      【解决方案2】:

      我在这里玩游戏有点晚了,但这非常容易。

      首先,使用 WithEvents 关键字创建您的 DataTable:

      Dim WithEvents theDataTable As New DataTable
      

      或者你可以使用 AddHandler 方法:

      AddHandler theDataTable.RowDeleted, AddressOf theDataTable_RowDeleted
      

      然后处理RowDeleted事件:

      Private Sub theDataTable_RowDeleted(sender As Object, e As DataRowChangeEventArgs) Handles theDataTable.RowDeleted
              theDataTable.Rows.Remove(e.Row)
      End Sub
      

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-26
        • 2016-08-15
        • 1970-01-01
        • 2012-06-30
        • 1970-01-01
        • 2022-10-06
        • 2015-05-04
        相关资源
        最近更新 更多