Spliting a DataTable into two dataTable


this code will split a data table into two data table according to the number of rows.

the following code will split a data table having some rows to the 2 data table with the number of rows provided by user.
if your data table contain 50 rows and you want to split it into two data table then provide the datatable and number of rows as input parameter and it will return the dataset having two datatable.



private DataSet SplitDataTable(DataTable dt,int noOfRowsInTable)
{
DataSet ds = new DataSet();
try
{

ds.Tables.Add(dt.Clone());
ds.Tables[0].TableName = "FirstSet";
ds.Tables.Add(dt.Clone());
ds.Tables[1].TableName = "SecondSet";
if (dt != null)
{
if (dt.Rows.Count > noOfRowsInTable)
{
for (int i = 0; i < noOfRowsInTable; i++)
{
DataRow dr = ds.Tables[0].NewRow();
for (int k = 0; k < dt.Columns.Count; k++)
{
dr[k]= dt.Rows[i][k];
}
ds.Tables[0].Rows.Add(dr);
}
for (int j = noOfRowsInTable; j < dt.Rows.Count; j++)
{
DataRow dr1 = ds.Tables[1].NewRow();
for (int l = 0; l < dt.Columns.Count; l++)
{
dr1[l] = dt.Rows[j][l];
}
ds.Tables[1].Rows.Add(dr1);
}
}

}
return ds;
}

catch (Exception ex)
{
lblDate.Text = ex.Message;
return ds;
}

}


Comments

Guest Author: vanessa10 Oct 2012

Hi, Here is a simply way to split more than 2 datatables:

public DataSet test(DataSet ds, int max)
{
int i = 0;
DataSet newDs = new DataSet();
DataTable newDt = ds.Tables[0].Clone();
newDt.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
newDt.Rows.Add(row);
i++;
if (i == max)
{
newDs.Tables.Add(newDt);
newDt = ds.Tables[0].Clone();
newDt.Clear();
i = 0;
}
}
return newDs;
}

Guest Author: vanessa10 Oct 2012

Sorry, this is correct code:

public DataSet test(DataSet ds, int max)
{
int i = 0;
int j = 1;
DataSet newDs = new DataSet();
DataTable newDt = ds.Tables[0].Clone();
newDt.TableName = "Table_" + j;
newDt.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
DataRow newRow = newDt.NewRow();
newRow.ItemArray = row.ItemArray;

newDt.Rows.Add(newRow);
i++;
if (i == max)
{
newDs.Tables.Add(newDt);
j++;
newDt = ds.Tables[0].Clone();
newDt.TableName = "Table_" + j;
newDt.Clear();
i = 0;
}
}
return newDs;
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: