Click here to Skip to main content
15,893,668 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
Need some feedback, I am trying to copy a column value from datagridview1 to dgv2. If I pressed the button for the first time, it will create a column with the column name from dgv1 and copy the values to an empty dgv2, which is correct.

However, when I press the button again, it will create a new column, but will replace all values in the first column. How do I set the column index so that each time I press the button, the values are copied to the correct column?

Thanks in advance.



C#
private void button4_Click(object sender, EventArgs e)
      {

          List<int> selectedColumns = new List<int>();
          foreach (DataGridViewColumn col in  dataGridView1.Columns)
          {
              if (col.Index == columIndexFromMouseDown)
             {
                  dataGridView2.Columns.Add((DataGridViewColumn)col.Clone());
                  selectedColumns.Add(columIndexFromMouseDown);
                  listBox1.Items.Add(col.Index);
              }

          }

              int rowIndex = 0;

              foreach (DataGridViewRow row in dataGridView1.Rows)
              {
                  dataGridView2.Rows.Add();
                  for (int i = 0; i < selectedColumns.Count ; i++)
                  {
                      if (dataGridView2.Columns.Count ==1)
                      {
                          dataGridView2.Rows[rowIndex].Cells[i].Value = row.Cells[selectedColumns[i]].Value;
                      }
                      if (dataGridView2.Columns.Count > 1)
                      {
                          MessageBox.Show("asf");
                      }
                  }

               rowIndex++;
              }

          }

      }
Posted
Comments
[no name] 4-Oct-12 6:28am    
on ur button 4 click please remove the added columns form datagridview2

datagridview2.columns.remove

and then do ur work ....reply me if it works

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900