You definitely don't want to do this:
clonedDGV = this.dataGridView1;
That line does not clone dataGridView1
. Instead, it just takes the variable clonedDGV
and points it to the same grid object that dataGridView1
points to. That means if you make any changes to clonedDGV
, you'll also be making them to dataGridView1
. Remember that in C#, (almost) all object variables are actually references to objects, not objects themselves.
There is no built in way to clone a DataGridView
in C#. If all you want to do is copy the structure to a new grid, then you can do something like this:
DataGridView clonedDGV = new DataGridView();
foreach(DataGridViewColumn col in this.dataGridView1.Columns) {
clonedDGV.Columns.Add(new DataGridViewColumn(col.CellTemplate));
}
That will give you a new grid with the same structure, but without any data. If you want to copy the data too, then loop through the rows in the original grid and add new rows to the new grid.
If there are other properties that need to be copied as well, just set them one by one on the new grid.
Edit: If all you care about is cloning the properties of your original grid, you'll have to do all the work yourself. If this is something you plan on doing often, I'd advise you to create an extension method and keep all your logic in there. Something like this:
public static class Extentions {
public static DataTable Clone(this DataGridView oldDGV) {
DataGridView newDGV = new DataGridView();
newDGV.Size = oldDGV.Size;
newDGV.Anchor = oldDGV.Anchor;
return newDGV;
}
}
Once that's been created you can call it like this:
DataGridView clonedDGV = dataGridView1.Clone();
You'll still have to write a line of code for each property that matters to you, but at least your logic will be in one place.