Click here to Skip to main content
11,438,782 members (74,417 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#3.0 C#4.0 Csharp.net
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.



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 4-Oct-12 0:33am
poiuyo171
Comments
vijay bisht at 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)



Advertise | Privacy | Mobile
Web01 | 2.8.150506.1 | Last Updated 4 Oct 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100