Retrieving datarows using DataTable.Select method and adding it to new DataTable

  • Thread starter C.Anand via DotNetMonster.com
  • Start date
C

C.Anand via DotNetMonster.com

Hi,
I have the following fragment of code which retrieves datarows from a data
table using the Select method.I want to add these rows into another data
table.But I get the Exception:
'Column "ReleaseDate" already belongs to another table'

// Use the Select method to find all rows matching the filter.
DataRow[] foundRows = dt.Select( strExpr, strSort,
DataViewRowState.CurrentRows);
int len = foundRows.Length;

DataColumn dc=new DataColumn();
foreach( DataRow r in foundRows )
{
foreach( DataColumn c in r.Table.Columns )
{
dc=c;
dt1.Columns.Add(c);
ColCnt=r.Table.Columns.IndexOf(c);
}
ii = 1;
}
dr=dt1.NewRow();
dr[ColCnt]=dc;
dt1.Rows.Add(dr);
}*/
 
M

Marina

Your problem has nothing to do with Select.

First off, there is no reason to say :dc = c, since it doesn't do a thing
for you. You don't even use the 'dc' variable anywhere. Also, instantiating
before the loop, has no effect, since you are just throwing that object away
when you say "dc = c"

The problem is that, you are adding datacolumns that belong to one table, to
another one. You can't do that, as the message clearly says.
 
C

C.Anand via DotNetMonster.com

Sorry,
Here is the code Fragment :
DataRow[] foundRows = dt.Select( strExpr, strSort,
DataViewRowState.CurrentRows);
DataRow dr;
int ColCnt=0;
DataColumn dc=new DataColumn();
foreach( DataRow r in foundRows )
{
foreach( DataColumn c in r.Table.Columns )
{
dc=c;
dt1.Columns.Add(c);
ColCnt=r.Table.Columns.IndexOf(c);
}

dr=dt1.NewRow();
dr[ColCnt]=dc;
dt1.Rows.Add(dr);
}
 
C

C.Anand via DotNetMonster.com

Should I add the table to a new dataset then?Or alternatively could I use
DataViews concept?
 
C

Cor Ligthert

C,

Normally you can clone your datatable and than use the importrow to get it
from the other table (or your selected collection) in a loop. Even to easy
to show it in code.

I hope this helps,

Cor
 
Top