Split DataTable into multiple Tables using C# and VB.Net in Windows Application

Last Reply 2 months ago By pandeyism

Posted 2 months ago

How can I divide all the datatable rows into two datagridview.

Lets say I have 15 rows in datatable and I want have 8 in datagridview1 and 7 in datagridview2

Eg

table0 

1

2

3

4

5

Now divide

table1

1

2

3

table2

4

5  

Posted 2 months ago

Hi satabeach

Refer below sample.

Code

C#

private void Form1_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)) });
    dt.Rows.Add(1, "Mudassar Khan");
    dt.Rows.Add(2, "John Hammond");
    dt.Rows.Add(3, "Suzanne Mathews");
    dt.Rows.Add(4, "Robert Schidner");
    dt.Rows.Add(5, "Mudassar Khan");
    dt.Rows.Add(6, "John Hammond");
    dt.Rows.Add(7, "Suzanne Mathews");
    dt.Rows.Add(8, "Robert Schidner");
    dataGridView1.DataSource = dt.Rows.Cast<DataRow>().Take(4).CopyToDataTable();
    dataGridView2.DataSource = dt.Rows.Cast<DataRow>().Skip(4).CopyToDataTable();
}

VB.Net

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String))})
    dt.Rows.Add(1, "Mudassar Khan")
    dt.Rows.Add(2, "John Hammond")
    dt.Rows.Add(3, "Suzanne Mathews")
    dt.Rows.Add(4, "Robert Schidner")
    dt.Rows.Add(5, "Mudassar Khan")
    dt.Rows.Add(6, "John Hammond")
    dt.Rows.Add(7, "Suzanne Mathews")
    dt.Rows.Add(8, "Robert Schidner")
    dataGridView1.DataSource = dt.Rows.Cast(Of DataRow)().Take(4).CopyToDataTable()
    dataGridView2.DataSource = dt.Rows.Cast(Of DataRow)().Skip(4).CopyToDataTable()
End Sub

Screenshot