Link to home
Start Free TrialLog in
Avatar of RohitYadav
RohitYadav

asked on

coverting Datarow[] to DataTable

I have a DataRow[] and I want to convert it to a DataTable. Is there any direct way of doing it or i need to read the DataRow[]   row by row and add one row at a time to the Table. Also if i do this, i would have to add equivalent columns to that new DataTable. Is there any direct way to get a DataTable with colums and the Rows added?
Thank you
Avatar of VBRocks
VBRocks
Flag of United States of America image

Hello RohitYadav,

How are you getting your array of rows?

Regards,

VBRocks
Avatar of RohitYadav
RohitYadav

ASKER

I am getting it using:
DataRow[] dRowUpdates = dTable.Select("Something");
Then i create the table with required columns and import rows to the new table.
Is there any better way?
Thanks again, i remember you helped me on my precious question also.

In this question I posted some code that can dynamically create datatables:

https://www.experts-exchange.com/questions/23211169/What's-almost-the-same-as-an-IDataReader.html
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

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
DataTable dFiltered = dTable.Clone();
This creates the required columns and also adds all the rows of the dTable.
I would need to remove the rows.
Anything better?
Thanks to all of you
dTable.Copy creates the required columns, and adds all the rows.  Clone only creates the columns.

DataTable.Clone method
http://msdn2.microsoft.com/en-us/library/system.data.datatable.clone(VS.80).aspx

Bob
Thanks very much, I just tried it. You were right. That solves half of the problem. Now is there any way we can add DataRow[] to the DataTable direcly without reading row by row?
Thanks very much again. This is a very  helpful place, I am getting to learn so much.
No, unfortunately you cannot import rows all at once.  Making a different suggestion would depend on what you need to accomplish with the resulting DataTable.

Bob
I suggest that Bob's answer at http:#a21043850 was the solution.   You need to create the columns first and you must add them one by one.

The only other thing you might consider is a DataView:
http://msdn2.microsoft.com/en-ca/library/system.data.dataview(VS.80).aspx

DataView view = new DataView(dTable, "Column= 'Value'", "", DataViewRowState.CurrentRows);

Note the Column = 'Value' represents a where condition.

Thanks very much Bob and to all who helped me.
How many records are in your table, and how many records are in your array?  It may be more practicle
to just filter your DataTable, and use the (filtered) DataView.

Then, if you really need the rows in a separate table, you can load them with very easily, without
looping through them.