Firstly I'm going to say that you will usually get quicker and better responses if you have a go at the problem yourself, and post code that you are having problems with.
There are also several examples via Google or in CodeProject of ways of splitting a datatable. However, to be fair, most of them seem to assume that you know the names of the columns you are trying to split on.
I've come up with this solution using this test data
const int noOfCols = 72;
DataTable dt = new DataTable();
for (int i = 0; i < noOfCols; i++)
dt.Columns.Add("ACol" + i.ToString(), typeof(string));
for (int j = 0; j < 100; j++)
{
DataRow dr = dt.Rows.Add();
for (int i = 0; i < noOfCols; i++)
dr.SetField<string>(i, "Row" + j.ToString() + ":" + "Col" + i.ToString());
}
First warning - all of my test data is of type
string
- you may need to change things around if you have different datatypes in your datatables.
2nd warning - note that I have chosen the number of columns
NoOfCols = 72
which doesn't divide exactly by 15. You should see why in the code below.
I've set up a variable for the column number to split on.
int splitCol = 15;
I also need somewhere to store my new datatables. As the .net
DataSet
conveniently already has a DataTable collection I'll use one of them
DataSet ds = new DataSet();
DataTable comes with a handy property called
DefaultView[
^]
Quote:
Gets a customized view of the table that may include a filtered view, or a cursor position.
I'm using that in the code below to get the new datatable based on a list of column names that I temporarily store in an array.
int startCol = 0;
int endCol = splitCol - 1;
while (startCol < dt.Columns.Count)
{
int newCols = (endCol < dt.Columns.Count) ? splitCol : dt.Columns.Count - startCol;
string[] ColNames = new string[newCols];
for (int i = 0; i < newCols; i++)
ColNames[i] = dt.Columns[startCol + i].ColumnName;
ds.Tables.Add(dt.DefaultView.ToTable(false, ColNames));
startCol += splitCol;
endCol += splitCol;
}