Spliting a DataTable into two dataTable

If he 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;
}

}

Advertisements

About Asif
Hello Friends… I have done my Bachelor of Engineering in Information Technology from Gujarat University. I have 1.7 years experience of web and windows based application development.. My basic idea to start a blog is to store all important link which help me in my application and access to every where. Also this information is help others who want to makes their application powerful. I am interested in .net framework (1.0,2.0,3.0,3.5 and more). This blog contain also many information related to SQL, Custom Controls in C#.net Please share your ideas and any query if you have...

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: