I want to cache a DataGridView row between ‘refreshes’ i.e. between a Rows.Clear() and a Columns.Clear(). However it seems that calling the Clear() methods does not unbind the data from the DataGridView instance, An example,
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); } }
This is done on a Form containing a DataGridView and a Button. Clicking the button twice gives the ‘Row provided already belongs to a DataGridView’ error.
There has been some discussion online about this that suggests that it may be a bug, however this was around 2004.
Once a row is part of a gridview, you can’t re-add it. The row itself keeps track of what DataGridView it is in. I would suggest making a copy of the cached row and adding the copy to the view. Since you make a new copy each time it won’t be in the view. Alternatively, you can go through and remove only those rows that have not been cached from the view, leaving the cached rows behind so that you don’t need to re-add it.