Programming for Everybody: C# DataGridView Paging | WinForms Pagination Step-by-Step (With Source Code)

C# DataGridView Paging | WinForms Pagination Step-by-Step (With Source Code)

 using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Data.SqlClient;

namespace WindowsFormsApplication2

{

    public partial class Form2 : Form

    {

        public Form2()

        {

            InitializeComponent();

        }

        SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=sports;Integrated Security=true");

        int pagerows;

        private void count_pages()

        {

            SqlCommand cmd = new SqlCommand("Select Count(*) From Table_reg3", conn);

            conn.Open();

            int count1;

            count1 = int.Parse(cmd.ExecuteScalar().ToString());

            pagerows = Convert.ToInt32(Math.Ceiling(count1 / (double)10));

            label3.Text = pagerows.ToString();

        }

        private void load_data()

        {

            int f1 = Convert.ToInt32(label1.Text) * (int)10 - Convert.ToInt32(10 + 1);

            int t1 = Convert.ToInt32(label1.Text) * (int)10;

            SqlCommand cmd2 = new SqlCommand("Select * From(Select Row_Number() Over(Order By id) As rownumber,id,name1,age,sport,points From Table_reg3) tablerow Where rownumber Between " + f1 + "And " + t1 + "", conn);

            SqlDataAdapter da = new SqlDataAdapter(cmd2);

            DataTable dt = new DataTable();

            da.Fill(dt);

            dataGridView1.DataSource = dt;

        }

        private void Form2_Load(object sender, EventArgs e)

        {

            count_pages();

        }


        private void button1_Click(object sender, EventArgs e)

        {

            label1.Text = 1.ToString();

            load_data();

        }


        private void button2_Click(object sender, EventArgs e)

        {

            if(Convert.ToInt32(label1.Text)< pagerows)

            {

                label1.Text = (Convert.ToInt32(label1.Text) + (int)1).ToString();

                load_data();

            }

        }


        private void button3_Click(object sender, EventArgs e)

        {

            if (Convert.ToInt32(label1.Text) > (int)1)

            {

                label1.Text = (Convert.ToInt32(label1.Text) - (int)1).ToString();

                load_data();

            }

        }


        private void button4_Click(object sender, EventArgs e)

        {

            label1.Text = pagerows.ToString();

            load_data();

        }

    }

}




No comments:

Post a Comment