Populate Windows Form DataGridView from specific range of rows using C# and VB.Net

Last Reply 7 months ago By pandeyism

Posted 7 months ago

I have datatable which has more than 15 rows and I wanted to bind rows from 5 - 10 in datagridview vb.net

Posted 7 months ago Modified on 7 months ago

Hi satabeach,

Please refer below sample.

Database

For this sample I have used of NorthWind database that you can download using the link given below.

Download Northwind Database

Namespaces

C#

using System.Data.SqlClient;

VB.Net

Imports System.Data.SqlClient

Code

C#

private void Form1_Load(object sender, EventArgs e)
{
    string constr = @"Server=.\SQL2005;DataBase=Northwind;UID=user;PWD=pass";
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT City, Country FROM Customers", con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                da.Fill(dt);
                var rows = dt.Select().Skip(5).Take(10);
                DataRow[] dr = rows.ToArray();
                DataTable dt1 = dr.CopyToDataTable();
                dataGridView1.DataSource = dt1;
            }
        }
    }
}

VB.Net

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim constr As String = "Server=.\SQL2005;DataBase=Northwind;UID=user;PWD=pass"
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("SELECT City, Country FROM Customers", con)
            Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                da.Fill(dt)
                Dim rows = dt.Select().Skip(5).Take(10)
                Dim dr As DataRow() = rows.ToArray()
                Dim dt1 As DataTable = dr.CopyToDataTable()
                dataGridView1.DataSource = dt1
            End Using
        End Using
    End Using
End Sub

Screenshot