Cloning a GUI Component

I need help as I'm relatively new to C #. I'm basically trying to clone the properties of the datagridview component (row / column content is different).

Basically I have a tab control ... and at runtime, if the user wants to add another table, a new page is created with a new datagridview object having the same properties as the existing datagridview component:

string newpagetitle = "tab_page" + (tab_control01.TabCount + 1);
TabPage newTab_page = new TabPage(newpagetitle);

DataGridView clonedDGV = new DataGridView();

clonedDGV = this.dataGridView1; //need to clone this
clonedDGV.Name=("DataGridView" + tab_control01.TabCount + 1);
clonedDGV.DataSource = exam_Results_Table;



source to share

2 answers

You definitely don't want to do this:

clonedDGV = this.dataGridView1;


This line does not clone dataGridView1

. Instead, it just takes a variable clonedDGV

and points it to the same grid object it points to dataGridView1

. This means that if you make any changes to clonedDGV

, you will also add them to dataGridView1

. Remember that in C # (almost) all object variables actually refer to objects, not objects.

There is no built-in way to clone a DataGridView

in C #. If all you want to do is copy the structure into 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));


This will give you a new grid with the same structure, but without any data. If you want to copy the data as well, then swipe through the lines in the original grid and add new lines to the new grid.

If there are other properties that need to be copied, just set them one by one to the new mesh.

Edit: If all you care about is cloning the properties of your original mesh, you'll have to do all the work yourself. If this is something you plan on doing often, I would suggest that you create an extension method and keep all your logic there. Something like that:

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 it has been created, you can call it like this:

DataGridView clonedDGV = dataGridView1.Clone();


You still have to write a line of code for every property that matters to you, but at least your logic will be in one place.



Instead, clonedDGV = this.dataGridView1

you need to go through the properties and copy them individually. Otherwise, you will reset clonedDGV

to be just another link to the old data grid.

Note: Usually an object is not "cloned" unless it is intended to be cloned.



All Articles