Link to home
Start Free TrialLog in
Avatar of Nalin Kumar Balaji Shanmugam
Nalin Kumar Balaji ShanmugamFlag for Ireland

asked on

To Create DataTable From DataRow Collection

Hi All,
    Can anybody clear my doubt ,
" How Can i create datatable from a collection of datarows."
Advance Thanx
Balaji.
ASKER CERTIFIED SOLUTION
Avatar of AerosSaga
AerosSaga

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AerosSaga
AerosSaga

I usually accomplish this with a datareader though:

Dim dt As New DataTable
dt.Columns.Add(New DataColumn("mHostCode", GetType(String)))
dt.Columns.Add(New DataColumn("mTotalFreq", GetType(Integer)))

...do your sql connection and command decleration...

dr = SqlCommand1.ExecuteReader(CommandBehavior.CloseConnection)
Dim datar As DataRow
While dr.Read
  datar = dt.NewRow
  datar(0) = dr(0)
  datar(1) = dr(1)
  dt.Rows.Add(datar)
End While
dr.Close
Hello Balaji,

In following example, I am creating DataTable from DataRow.

----------------------------------------------------------------------------------------------------------------

DataTable dt = new DataTable();
DataView dv;
DataRow dr;
      
                dt.Columns.Add( new DataColumn("Column0",Type.GetType("System.String") ) );
      dt.Columns.Add( new DataColumn("Column1",Type.GetType("System.String") ) );
                        
      dr = dt.NewRow();                                                  //Create 1st Row
      dr[0] = "row1:Column0";
      dr[1] = "row1:Column1";
      
      dt.Rows.Add(dr);                                                   // Add 1st row to table
               
                    dr = dt.NewRow();                                                 //Create 2nd Row
      dr[0] = "row2:Column0";
      dr[1] = "row2:Column1";
      dt.Rows.Add(dr);                                                   // Add 2nd row to table

      dv = new DataView( dt );

----------------------------------------------------------------------------------------------------------------


-tushar
Avatar of Snarf0001
If the rows already belong to a datatable, if you're getting them from a DataTable.Select for example, you need to use

  myDataTable.ImportRow(myDataRow)
Mine and AerosSaga's code does exactly what user is asking for. But the points should go to AerosSaga as he showed 2 correct alternative method before me.

-tushar
thank you tushar...I happily agree....Aeros
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial