Click here to Skip to main content
15,915,750 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
hello everybody... i want to find a way to copy some specific columns from a datagrid to another (in the same form) by using a button... any ideas??

i am using visual studio 2010
Posted
Comments
Shahin Khorshidnia 5-Apr-12 14:59pm    
You must tag your question. What kind of application are you working on? Windows, ASP.Net, WPF? Mobile, ....?

1 solution

The following code will copy each row from one grid to another.
C#
foreach (DataRow row in dataTable1.Rows)
{
    dataTable2.Rows.Add(row.ItemArray);
}


If you want to copy some specific columns use a if statment while copying to the other grid. So it becomes:
C#
foreach (DataRow row in dataTable1.Rows)
{
  if(Condition)
  {
     dataTable2.Rows.Add(row.ItemArray);
  }
}


Good luck,
OI
 
Share this answer
 
Comments
panagiotis13g 5-Apr-12 14:31pm    
it throws this exception for the first case you send me...

An unhandled exception of type 'System.InvalidCastException' occurred in aaaa.exe

Additional information: Unable to cast object of type 'System.Windows.Forms.DataGridViewRow' to type 'System.Data.DataRow'.
Orcun Iyigun 5-Apr-12 15:13pm    
Please change the DataRow to DataGridViewRow/GridViewRow.
panagiotis13g 7-Apr-12 16:11pm    
i tried what you suggested me but it throws the same exception...

any more ideas??
Orcun Iyigun 7-Apr-12 17:31pm    
Please check these 3 links
link 1[^]
link 2[^]
link 3[^]
lalaou 5-Apr-12 17:31pm    
you mean this:
private void button1_Click(object sender, EventArgs e)
{

foreach (DataGridViewRow row in table1DataGridView.Rows)
{
copyDataGridView.Rows.Add(row.ItemArray);
}
}
????
because its still throw the same exception!

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