Copy DataGridView columns to another grid

flynn

Regular
Joined
Jul 28, 2005
Messages
59
I have 2 DataGridView controls on my search form. I have manually created the columns for the 1st grid, but now I want to dynamically duplicate those columns in the 2nd grid.

Using the code below, I get this error: "Provided column already belongs to the DataGridView control."

Code:
Control[] ctl = CustomerSearch.Controls.Find("dgvSearch",false);            
            
foreach (DataGridViewColumn dgvCol in ((DataGridView)ctl[0]).Columns)
{
     dgvSelected.Columns.Add(dgvCol);
}

I'm not sure what the error is trying to tell me. The dgvSelected grid has 0 (zero) columns before this code is ran. "CustomerSearch" is a user-control that contains a DataGridView control called "dgvSearch".

Any ideas as to why I am getting this error?

tia,
flynn
 
I finally figured it out. Duh!

I had to add the following code to dynamically create the new columns, then clone the original columns.

Code:
foreach (DataGridViewColumn dgvCol in dgv1.Columns)
{
[COLOR="Red"]
     DataGridViewColumn dgvNewCol = new DataGridViewColumn();
     dgvNewCol = (DataGridViewColumn)dgvCol.Clone();
[/COLOR]
     dgv2.Columns.Add(dgvNewCol);     
}
 
Unnecessary instantiation

It's not hugely important, but your code is instantiating a DataGridViewColumn which is unused, as the subsequent line of code overwrites the variable with the cloned column. This should work just as well:

C#:
foreach (DataGridViewColumn dgvCol in dgv1.Columns)
    dgv2.Columns.Add((DataGridViewColumn) dgvCol.Clone());

Good luck :)
 
Back
Top