Clone & Copy Methods Of DataTable ADO.NET | ADO.NET Tutorials DataTable C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace Copy_Clone_DataTable
{
internal class Program
{
static void Main(string[] args)
{
try
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
string query = "select * from employee_tbl";
SqlDataAdapter sda = new SqlDataAdapter(query,con);
DataTable employees = new DataTable();
sda.Fill(employees);
Console.WriteLine("Original Data Table");
foreach(DataRow row in employees.Rows)
{
Console.WriteLine(row["id"] + " " + row["name"] + " " + row["gender"] + " " + row["age"] + " " + row["salary"] + " " + row["city"]);
}
DataTable CopyDataTable = employees.Copy();
Console.WriteLine("Copy Data Table");
foreach(DataRow row in CopyDataTable.Rows)
{
Console.WriteLine(row["id"] + " " + row["name"] + " " + row["gender"] + " " + row["age"] + " " + row["salary"] + " " + row["city"]);
}
DataTable CloneDataTable = employees.Clone(); //Clone() method will copy only structure(Columns), Not rows
Console.WriteLine("Clone DataTable");
if (CloneDataTable.Rows.Count > 0)
{
foreach(DataRow row in CloneDataTable.Rows)
{
Console.WriteLine(row["id"] + " " + row["name"] + " " + row["gender"] + " " + row["age"] + " " + row["salary"] + " " + row["city"]);
}
}
else
{
//Console.WriteLine("Rows Not Found...");
CloneDataTable.Rows.Add(1,"Tarun","Male",25,45000,"Ahmedabad");
CloneDataTable.Rows.Add(2,"Prakash","Male",26,67000,"Mumbai");
}
foreach(DataRow row in CloneDataTable.Rows)
{
Console.WriteLine(row["id"] + " " + row["name"] + " " + row["gender"] + " " + row["age"] + " " + row["salary"] + " " + row["city"]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
.png)
.png)
.png)
Comments
Post a Comment