【发布时间】:2011-06-15 14:32:45
【问题描述】:
我有一个 DataTable(通过 DataGridView 显示)并希望重用它来手动填写不同的数据。所以工作流程是:
每次我需要重新填充 DataTable 时,我都会这样做:
- 从 DataGridView 中解开 DataTable。
- 清除 DataTable 内容。
- 手动将 DataColumns 和 DataRows 添加到 DataTable。
- 用 DataGridView 再次挂钩 DataTable。
要实现第 0 步,我只需执行以下操作:DataGridView.DataSource = null。
为了实现第 1 步,我调用了 DataTable.Clear()、DataTable.Rows.Clear() 和 DataTable.Columns.Clear()。
为了实现第 3 步,我调用 DataGridView.DataSource = DataTable。
第2步以正常方式完成,我跳过代码。
每当 DataGridView 更新了新内容时,如果我单击 DataGridView 列进行排序,下次更新 DataTable 时,我会在步骤 2 中尝试添加新行时出现空引用异常。但如果我从不点击 DataGridView 列进行排序,一切正常。
我猜这与排序有关。但我不知道是什么导致了空引用异常。 DataTable 是否有可能尝试搜索旧内容中的某些键但找不到?由于第 1 步,它当然无法找到旧内容。清除旧 DataTable 内容的正确方法是什么,以便在我填写新内容时它永远不会引用旧内容?
谢谢。
【问题讨论】:
-
为什么不直接新建一个DataTable呢?通过增加这种复杂性,您可以获得什么?