Click here to Skip to main content
15,311,561 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello ,

I Have one DataTable with Columns as SlNo,FirstName,LastName,MobileNO and Salary,

i want to Copy only SlNo,FirstName,LastName and Salary to anothere table .....

Using Loops i want to add Data

What I have tried:

newTable = dt.DefaultView.ToTable(false, ColumnName);

i want add through loop of data table copy to another table
Posted
Updated 23-Nov-16 20:24pm

1 solution

Use Copy method and remove desired columns
C#
DataTable newTable ;
newTable = dt.Copy();


or you can clone datatable structure and by looping add rows to new table

C#
DataTable newTable = dt.Clone();
   foreach (DataRow item in dt.Rows)
   {
    newTable.ImportRow(item);
   }



for column removal use one of below
C#
dt.Columns.Remove("columnName");
dt.Columns.RemoveAt(columnIndex);


Updated solution:
C#
DataTable dt = new DataTable();
dt.Columns.Add("[Serial Number]", typeof(int));
dt.Columns.Add("[Last Name]", typeof(string));
dt.Columns.Add("[First Name]", typeof(string));
dt.Columns.Add("Salary", typeof(decimal));
dt.Columns.Add("[Mobile No]", typeof(string));

dt.Rows.Add(1, "Kulkarni", "Ramesh", 1500.00, "9485234567");
dt.Rows.Add(2, "rani", "suresh", 1500.00, "9485234567");



DataTable newTable;
newTable = dt.Copy();
newTable.Columns.Remove("[Mobile No]");
newTable.AcceptChanges();
   
v2
Comments
Darshan E Ksheerasagar 24-Nov-16 2:39am
   
--------------------------------------------------------------------------------
Serial Number Last Name First Name Salary Mobile No.
--------------------------------------------------------------------------------
1 Kulkarni Ramesh 1,500.00 9,48,56,21,025.00
2 Rani Suresh 2,500.00 8,95,10,25,469.00
--------------------------------------------------------------------------------


---------------------------------------------------------------
Serial Number Last Name First Name Salary
---------------------------------------------------------------
1 Kulkarni Ramesh 1,500.00
2 Rani Suresh 2,500.00
---------------------------------------------------------------

First Table is my Original table Second is want i want my result .
manu_dhobale 24-Nov-16 3:17am
   
Please check updated solution

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