Wednesday, January 12, 2011

Copy DataRows form DataTables to another

using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;

namespace ImportRowFromDataTable
{
class Class1
{
static void Main(string[] args)
{
int tbl_1count;
int tbl_2count;
int i;

// Add code to start application here.
DataTable tbl_1 = new DataTable();
DataTable tbl_2 = new DataTable();

// Change the connection string to your server.
SqlConnection Con = new SqlConnection("Connectionstring");

// Create the DataAdapter.
SqlDataAdapter da = new SqlDataAdapter("Select * from tbl_1", Conn);

// Fill the DataSet with data.
DataSet ds = new DataSet();
da.Fill(ds, "tbl_1");
tbl_1 = ds.Tables["tbl_1"];
tbl_1count = tbl_1.Rows.Count;

// Write the number of rows in the Products table to the screen.
Console.WriteLine("Table tbl_1has " + tbl_1count.ToString() + " Rows.");

// Loop through the five rows, and disply the first column.
for (i = 0; i <= 4; ++i)
{
Console.WriteLine("Row(" + i.ToString() + ") = " + tbl_1.Rows[i][1]);
}

// Use Clone method to copy the table tbl_1 structure.
tbl_2 = tbl_1.Clone();

// Use the ImportRow method to copy from tbl_1's data to its clone.
for (i = 0; i <= 4; ++i)
{
tbl_2.ImportRow(tbl_1.Rows[i]);
}
tbl_2count = tbl_2.Rows.Count;


// Write the number of rows in tbl_2table to the screen.
Console.WriteLine("Table tbl_2 has " +tbl_2count.ToString() + " Rows");

// Loop through the rows of tbl_2, and display.
for (i = 0; i <= tbl_2count - 1; ++i)
{
Console.WriteLine("Row(" + i.ToString() + ") = " + tbl_2.Rows[i][1]);
}

Console.ReadLine();

}
}
}

No comments:

Post a Comment