Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good Evening all of us

I have the access database.
On the database there are two tables. Then I want to import data from one table to another table

I am writing this code but it has taken error


C#
foreach (DataRow dr in sourceTable.Rows)
{
    destinationTable.ImportRow(dr);
}


////////////////////


foreach (DataRow dr in sourceTable.Rows)
{
    r = destinationTable.NewRow;
    r("Name") = dr["Name"];
    r("City") = dr["City"];
    r("Cost") = dr["Cost"];
    destinationTable.Rows.Add(r);
}



so can u give me guidance in for loop condition

[edit]pre tag for C# code added. Spelling mistakes corrected - PES[/edit]
Posted
Updated 1-Mar-12 2:49am
v2
Comments
Oshtri Deka 1-Mar-12 9:39am    
Syntax errors!
To get row's field via indexer only square ([]) brackets work.
r("Name") wrong!
r["Name"] correct.

In the source table, if any modification is done the RowState of the data row will be Modified state. Due to this the RowState of the imported row cannot be set to Added state. Hence, you have to first call AcceptChanges method on the source table and then import the rows as follows

C#
sourceTable.AcceptChanges();
foreach (DataRow dr in sourceTable.Rows)
{
    destinationTable.ImportRow(dr);
    //Set the row state of the newly row added row to Added state.
    destinationTable.Rows(destinationTable.Rows.Count - 1).SetAdded();
}


You may accept and vote one of the solutions which solved your problem, otherwise please post your queries.
 
Share this answer
 
v2
Why don't you try with Merge() method. No loops and I guess you don't have great schema difference between tables.
C#
//
destinationTable.Merge(sourcetable);
//
 
Share this answer
 
two tables in the same database..um
how about running SQL-Script in access?

C#
string sqlscript = @"
Insert into destTable(FieldA,FieldB,FieldC)
Select FieldA,FieldB,FieldD
from SourceTable";

cmd.CommandText=sqlscript;
cmd.ExecuteNonQuery();


http://office.microsoft.com/en-us/access-help/insert-into-statement-HA001231488.aspx[^]
 
Share this answer
 
Dear anilksrk,
Try the following,
C#
foreach(datarow dr in sourcetable.rows)
{
destinationTable.rows.add(dr);
destinationTable.AcceptChanges();
}


Regards,
Bluesathish
 
Share this answer
 
Comments
ProEnggSoft 1-Mar-12 8:44am    
If AcceptChanges method is called on destinationTable, then the RowState of the data rows will be set to Unchanged state, so that when the data is to be saved to the database the data will not be added to the database on the disk.

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