Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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."

 

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

Posted

I finally figured it out. Duh!

 

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

 

foreach (DataGridViewColumn dgvCol in dgv1.Columns)
{
[color="Red"]
    DataGridViewColumn dgvNewCol = new DataGridViewColumn();
    dgvNewCol = (DataGridViewColumn)dgvCol.Clone();
[/color]
    dgv2.Columns.Add(dgvNewCol);     
}

Posted

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:

 

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

 

Good luck :)

Never trouble another for what you can do for yourself.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...