0

I have a question about DGV in windows Forms. So I have dgv1 where is written some information. Then I am filling second dgv2 with this code:

dataGridView2.DataSource = dataGridView1.DataSource;

and it works fine, but when I am changing something in dgv2 (removing row or column), it appears on dgv1 too. I can't understand why. I am just adding data from dgv1 into dgv2 and I want dgv1 to be so how it is (without changes). At the same time I want to change dgv2 and see the difference(between dgv1 and dgv2).

So who has idea why is it happening ?

I have solved it with this code:

dataGridView2.Columns.Add("Column1", "Name");
dataGridView2.Columns.Add("Column2", "Date");
dataGridView2.Columns.Add("Column3", "Time");
DataGridViewRow row = new DataGridViewRow();

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    row = (DataGridViewRow)dataGridView1.Rows[i].Clone();
    int intColIndex = 0;

    foreach (DataGridViewCell cell in dataGridView1.Rows[i].Cells)
    {
        row.Cells[intColIndex].Value = cell.Value;
        intColIndex++;
    }

    dataGridView2.Rows.Add(row);
}

dataGridView2.AllowUserToAddRows = false;
dataGridView2.Refresh();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dave Dave
  • 21
  • 6
  • 1
    It's about reference types. `DataSource` property of Both `DataGridView` controls are pointing to a single object. – Reza Aghaei Feb 26 '17 at 23:08
  • See also https://stackoverflow.com/questions/24089591/reference-type-vs-value-type, https://stackoverflow.com/questions/1219664/c-sharp-reference-type-assignment-vs-value-type-assignment, https://stackoverflow.com/questions/1205444/value-type-vs-reference-type-object-class-c-sharp, or any number of other discussions that explain what a reference type in C# is, how it works, and the implications of using them. Also read http://www.yoda.arachsys.com/csharp/parameters.html for a detailed explanation of these issues. – Peter Duniho Feb 26 '17 at 23:10
  • See also https://stackoverflow.com/questions/8148385/weird-value-referencing, https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c, https://stackoverflow.com/questions/4739213/in-c-use-of-value-types-vs-reference-types, https://stackoverflow.com/questions/32010172/what-is-the-difference-between-a-variable-object-and-reference, and https://stackoverflow.com/questions/7513691/c-sharp-managed-code-reference-type-question, to name a few more. – Peter Duniho Feb 26 '17 at 23:19

1 Answers1

0

Simple: You are using exactly the same DataSource for both DataGridViews, not a copy.

That means: If you change anything in the datasource, all DataGridViews using it will update accordingly. You may want to clone your datasource before assigning it to the second DataGridView

Psi
  • 6,387
  • 3
  • 16
  • 26