Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
4.60/5 (5 votes)
See more:
Hi !! Have a good day

I have a question, please help me !
I want to split a datatable into many datatables, how to do that by c#.net.
Example : datatable is: DA has 250 rows ==> split into 3 datatable : DA1 (100rows) , DA2(100 rows), DA3(50rows)
If datatable DA has 1000 rows, ==> split into 10 datatables, ( thats mean one datatable have less than 100rows)

Thanks for your help!
Posted

You will have to loop through the rows and copy them into a new datatable. You can also use DataTable.Select method as well instead of looping through all the rows.

 
Share this answer
 
The simplest way would be to write a loop that iterated over the DataTable and allocate rows accordingly. When you do this, you need to clone the table structure, and use ImportRow to copy the row from one table to another. If you attempt to copy the row over directly, you'll get a "row belongs to another table" error. The following method does what you want:
private List<DataTable> CloneTable(DataTable tableToClone, int countLimit)<br />{<br />    List<DataTable> tables = new List<DataTable>();<br />    int count = 0;<br />    DataTable copyTable = null;<br />    foreach (DataRow dr in tableToClone.Rows)<br />    {<br />        if ((count++ % countLimit) == 0)<br />        {<br />            copyTable = new DataTable();<br />            // Clone the structure of the table.<br />            copyTable = tableToClone.Clone();<br />            // Add the new DataTable to the list.<br />            tables.Add(copyTable);<br />        }<br />        // Import the current row.<br />        copyTable.ImportRow(dr);<br />    }<br />    return tables;<br />}


 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900