Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi guys!

I have a form which has two datagrids.i want with a button to copy the selected rows
from one to another.
I find this code :
C#
private void button1_Click(object sender, EventArgs e)
       {

           foreach (DataGridViewRow row in this.table1DataGridView.SelectedRows)
           {
               object[] rowData = new object[row.Cells.Count];
               for (int i = 0; i < rowData.Length; ++i)
               {
                   rowData[i] = row.Cells[i].Value;
               }
               this.copyDataGridView.Rows.Add(rowData);
           }
       }

but it throw an exception:

Additional information: Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.
Posted
Updated 28-Feb-17 22:22pm

Hi,
I've created a sample for you which is very simple but works fine:
C#
private void button1_Click(object sender, EventArgs e)
      {
          List<object> destList= new List<object>();
          foreach (DataGridViewRow row in dataGridView1.SelectedRows)
              destList.Add(row.DataBoundItem);
          dataGridView2.DataSource = destList;
      } 


dataGridView1's datasource is a dataset which is databound.

Cheers.
 
Share this answer
 
Comments
lalaou 8-Apr-12 18:58pm    
THANK you very much!!!!
thanks thanks thanks! :)
Reza Ahmadi 8-Apr-12 23:30pm    
Your welcome!
lalaou 10-Apr-12 20:53pm    
Hi again! i run the code and i realize that i can copy only one row. if i try to do it for a second time it replace the first copy could you please show me a way so i can can keep more than one copies
Reza Ahmadi 11-Apr-12 3:14am    
Actually your question is not very clear. However, if you want to keep more than one copy you can use Dictionary<string,list&lt;object>>. 'string' is your key which is used to find a particular List<object> which can be bound to a destination grid.]
Cheers
Hi,
As from the Exception message is clear, in the destination DataGrid you need to clear databinding tags as you want to add rows programmatically.

Cheers
 
Share this answer
 
Comments
Reza Ahmadi 7-Apr-12 6:34am    
Hi,
My point is to define an empty grid as your destination grid. Then, according to selected rows(I presume you can find record keys from the selected rows) you filter your main data source. Then, you will bind the new filtered data to the destination grid.

I hope it will help,
Cheers.
lalaou 7-Apr-12 16:22pm    
i have an empty grid as destination...
can you tell me what is wrong in the code i posted or can you show the correct one?
i appreciate your help!

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