c# - 如何缓存一行而不引发 "Row provided already belongs to a DataGridView"错误?

标签 c# .net winforms datagridview

我想在“刷新”之间缓存 DataGridView 行,即在 Rows.Clear()Columns.Clear() 之间。但是,调用 Clear() 方法似乎不会解除数据与 DataGridView 实例的绑定(bind),例如,


    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        DataGridViewRow cachedRow = new DataGridViewRow();

        private void button1_Click(object sender, EventArgs e)
        {
            this.dataGridView1.Rows.Clear();
            this.dataGridView1.Columns.Clear();
            DataGridViewColumn aColumn = new DataGridViewTextBoxColumn();
            this.dataGridView1.Columns.Add(aColumn);
            this.dataGridView1.Rows.Add(cachedRow);
        }
    }

这是在包含 DataGridViewButton 的表单上完成的。单击该按钮两次会出现“提供的行已属于 DataGridView”错误。

网上对此有一些讨论,表明这可能是一个错误,但那是在 2004 年左右。

最佳答案

一旦一行成为 gridview 的一部分,您就无法重新添加它。该行本身 keeps track of what DataGridView我建议制作缓存行的副本并将副本添加到 View 中。由于您每次都会创建一个新副本,因此它不会出现在 View 中。或者,您可以浏览并仅删除 View 中未缓存的行,保留缓存的行,这样您就不需要重新添加它。

关于c# - 如何缓存一行而不引发 "Row provided already belongs to a DataGridView"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/598627/

相关文章:

c# - ExecuteScalar() 总是返回 NULL

c# - 列表计数和 null 的条件

c# - 通过正则表达式分割字符串

.net - 如何对使用 PetaPoco.Database 的服务进行单元测试

.net - UI线程访问外部控制

c# - 是否可以在同一解决方案中使用带有单独类库的后台 worker

c# - 序列化 System.Globalization.CultureInfo 类型的对象时检测到循环引用

c# - 找不到Q#AggregateException

.net - future 的(Windows)桌面应用开发 : the future of WPF and Silverlight

c# - 翻转/滑动效果与 Winforms