tags:

views:

104

answers:

2

Hi I have a datatable with 5 columns and I would like to copy only two of those columns to another datatable. What is the best way to do this?

DataTable 1:

col1 col2 col3 col4 col5
1    2    3    4    5
6    7    8    9    10

DataTable 2:

col1 col2
1    2  
6    7

Thanks

A: 

Would something like this be efficent?

        DataTable myTable = new DataTable();
        myTable.Columns.Add("Col1");
        myTable.Columns.Add("Col2");
        myTable.Columns.Add("Col3");
        myTable.Columns.Add("Col4");
        myTable.Columns.Add("Col5");
        myTable.Rows.Add(new object[] { "hey", "hey", "Hey", "hey", "Hey" });
        GridView1.DataSource = myTable;
        GridView1.DataBind();

        DataTableReader myReader = myTable.CreateDataReader();

        DataTable myTable2 = new DataTable();
        myTable2.Load(myReader);
        myTable2.Columns.Remove("Col3");
        myTable2.Columns.Remove("Col4");

        GridView2.DataSource = myTable2;
        GridView2.DataBind();
DavidS
A: 

or you could clone the datetable and remove the columns you dont want/need

DataTable dtTest = dtAllData.Clone();
dtTest.Columns.Remove("col3");
dtTest.Columns.Remove("col4");
d1k_is
I don't belive Clone copies data, so you would probably still need to iterate through and copy the columns for each row.
Si
not too sure but it seemed to work when i tried it, tho i cant remember 100%
d1k_is