locked
Split Datatable by columns to other Datatables RRS feed

  • Question

  • I have a dataTable and I want each seperate column with its values, to be stored to a new Datatable. For example: a datatable dt with ID,FName, LName as columns. I want three new Datatables with one column each dt1(ID),  dt2(FName). dt3(LName).
     
    How can i do that?
    Thanks.
    Wednesday, January 13, 2010 10:44 AM

Answers

  • DataTable[] dts = new DataTable[dt.Columns.Count];
    for(int ti=0;ti<dts.Length;ti++)
    {
      dts[ti]=new DataTable();
      dts[ti].Columns.Add(dt.Columns[ti].ColumnName,dt.Columns[ti].DataType);
    }
    foreach(DataRow dr in dt.Rows)
    {
      for(int ti=0;ti<dts.Length;ti++)
         dts[ti].Rows.Add(new object[]{dr[ti]});
    }

    With best regards, Yasser Zamani
    • Proposed as answer by Huan Li Thursday, January 14, 2010 6:31 AM
    • Marked as answer by Bin-ze Zhao Friday, January 15, 2010 9:07 AM
    Wednesday, January 13, 2010 8:48 PM