Introduction
This article provides an example of loading the data into a DataGridView on scroll down.
Step 1
First we create a table in a database as in the following:
- CREATE TABLE Table1
- (
- id int identity(1,1),
- Column1 int,
- Column2 int
- )
Step 2
Now put data into the table (for a better understanding I filled in 1 to 60 numbers).
Step 3
Create a New Windows Form application. Drag and drop a DataGridView into a Windows Forms form.
Go to the form's properties then events then the Load event and then press the Enter key.
Now go to the DataGridView's properties then events then scroll and then press the Enter key.
Now go to the DataGridView properties then events then SelectionChanged and then press the Enter key.
Step 4
Now paste in the code.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.SqlClient;
-
- namespace LoadGridView
- {
- public partial class Form1 : Form
- {
- SqlConnection con = new SqlConnection("data source=Rahul-pc\\rahul_pc;initial catalog=example;integrated security=true;");
- DataTable dt = new DataTable();
- DataSet ds;
- BindingSource bi = new BindingSource();
- SqlDataAdapter da;
- int pageIndex = 1;
- int PageSize = 20;
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- LoadGridView();
- }
-
- private void LoadGridView()
- {
- string str = "select * from Table1 where id between "+pageIndex+" and "+PageSize;
- da = new SqlDataAdapter(str,con);
- ds = new DataSet();
- da.Fill(ds);
- dt = ds.Tables[0];
- bi.DataSource = dt;
- dataGridView1.DataSource = bi;
- dataGridView1.ClearSelection();
- }
-
- private int GetDisplayedRowsCount()
- {
- int count = dataGridView1.Rows[dataGridView1.FirstDisplayedScrollingRowIndex].Height;
- count = dataGridView1.Height / count;
- return count;
- }
-
- private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
- {
- int display = dataGridView1.Rows.Count - dataGridView1.DisplayedRowCount(false);
- if (e.Type == ScrollEventType.SmallIncrement || e.Type == ScrollEventType.LargeIncrement)
- {
- if (e.NewValue >= dataGridView1.Rows.Count - GetDisplayedRowsCount())
- {
- string str = "select * from Table1 where id between " + ((pageIndex * PageSize) + 1) + " and " + ((pageIndex + 1) * PageSize);
- da = new SqlDataAdapter(str, con);
- ds = new DataSet();
- da.Fill(ds);
- dt.Merge(ds.Tables[0]);
- bi.DataSource = dt;
- dataGridView1.ClearSelection();
- dataGridView1.FirstDisplayedScrollingRowIndex = display;
- pageIndex++;
- }
- }
- }
-
- private void dataGridView1_SelectionChanged(object sender, EventArgs e)
- {
- dataGridView1.ClearSelection();
- }
- }
- }
Now run the project and see that when you scroll down, data will be loaded.
I hope you understand how to add data from a database into a DataGridView on scroll down.