flynn Posted January 5, 2007 Posted January 5, 2007 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 Quote
flynn Posted January 5, 2007 Author Posted January 5, 2007 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); } Quote
MrPaul Posted January 5, 2007 Posted January 5, 2007 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 :) Quote Never trouble another for what you can do for yourself.
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.