Saturday, 12 July 2014

paging in datagridview in windows form application using c#



Description:

            In this example we explain that how to create Paging in Datagrid view in window application using C# with Insert,Update,Delete in Data Grid View in C# window application. We already explain many example like Paging in gridview  in web application. But in this example we explain that in how to Paging with First,Next,Previous,Last button to navigate the record in Datagridview in window application using C#.


Here we create a Custom Paging in Datagridview because DataGrid view does not provide paging facility like we have use in Gridview in Asp.Net. so to create custom paging in datagridview follow the below code.

to Show Example Of How to Create Paging or Custom Paging in Reapeter so plz click Here Paging or Custom Paging in Reapeter Control


to Show Example of How to Create Insert,Update,Delete in Gridview plz Click Here CRUD operation in GridView


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;
using Microsoft.CSharp;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;


namespace windowgarrage
{
    public partial class cardetail : Form
    {
        public static int empid;
        private int PgSize = 5;
        private int CurrentPageIndex = 1;
        private int TotalPage = 0;

        SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\kirit\windowgarrage\windowgarrage\Database1.mdf;Integrated Security=True");

           public cardetail()
        {
            InitializeComponent();
            //    scrollVal = 0;
        }

        private DataTable GetCurrentRecords(int page, SqlConnection con)
        {
            DataTable dt = new DataTable();
            SqlDataAdapter adp1 = new SqlDataAdapter();
            SqlCommand cmd2 = null;
            if (page == 1)
            {
                cmd2 = new SqlCommand("Select TOP " + PgSize +
                " id,carno,carname,address,personname,cellno,detail,total,dating from cardetail ORDER BY id", con);
            }
            else
            {
                int PreviousPageOffSet = (page - 1) * PgSize;

                cmd2 = new SqlCommand("Select TOP " + PgSize +
                    "id, carno,carname,address,personname,cellno,detail,total,dating from cardetail WHERE id NOT IN " +
                    "(Select TOP " + PreviousPageOffSet +
            "id from cardetail ORDER BY id) ", con);
            }
            try
            {
                // con.Open();
                adp1.SelectCommand = cmd2;
                adp1.Fill(dt);
                CalculateTotalPages();


            }
            finally
            {
                con.Close();
            }
            return dt;
        }

        private void CalculateTotalPages()
        {
            int rowCount = countrows();
            TotalPage = rowCount / PgSize;
            // if any row left after calculated pages, add one more page
            if (rowCount % PgSize > 0)
                TotalPage += 1;
        }
      

      
        private int countrows()
        {
            try
            {
                DataTable dt = new DataTable();
                string query = "select * from cardetail";

                SqlCommand cmd = new SqlCommand(query, cn);
                SqlDataAdapter sa = new SqlDataAdapter();
                sa.SelectCommand = cmd;

                cn.Open();
                cmd.ExecuteNonQuery();
                sa.Fill(dt);
                return dt.Rows.Count;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cn.Close();
            }
        }
      
      
      

        private void cardetail_Load(object sender, EventArgs e)
        {

            dataGridView2.DataSource = GetCurrentRecords(CurrentPageIndex, cn);
            dataGridView2.AutoGenerateColumns = false;
            dataGridView2.AllowUserToAddRows = false;


            DataGridViewLinkColumn Editlink = new DataGridViewLinkColumn();
            Editlink.UseColumnTextForLinkValue = true;
            Editlink.HeaderText = "Edit";
            Editlink.DataPropertyName = "lnkColumn";
            Editlink.LinkBehavior = LinkBehavior.SystemDefault;
            Editlink.Text = "Edit";

            dataGridView2.Columns.Add(Editlink);
            DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn();
            Deletelink.UseColumnTextForLinkValue = true; Deletelink.HeaderText = "delete";
            Deletelink.DataPropertyName = "lnkColumn";
            Deletelink.LinkBehavior = LinkBehavior.SystemDefault;
            Deletelink.Text = "Delete";
            dataGridView2.Columns.Add(Deletelink);

            DataGridViewLinkColumn Printlink = new DataGridViewLinkColumn();
            Printlink.UseColumnTextForLinkValue = true; Deletelink.HeaderText = "print";
            Printlink.DataPropertyName = "lnkColumn";
            Printlink.LinkBehavior = LinkBehavior.SystemDefault;
            Printlink.Text = "Print";
            dataGridView2.Columns.Add(Printlink);

        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string a = DateTime.Now.ToShortDateString();
                string query = "Insert into cardetail values('" + textBox8.Text + "','" + textBox9.Text + "','" + textBox10.Text + "','" + textBox11.Text + "','" + textBox12.Text + "','" + textBox13.Text + "','" + Convert.ToDouble(textBox14.Text) + "','" + Convert.ToDateTime(a) + "',null)";

                SqlCommand cmd = new SqlCommand(query, cn);
                cn.Open();
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record Inserted Successfully.....");
                cn.Close();
                clear();
                // binddata();
                dataGridView2.DataSource = GetCurrentRecords(CurrentPageIndex, cn);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string a = DateTime.Now.ToShortDateString();
                string query = "update cardetail set carno='" + textBox8.Text + "',carname='" + textBox9.Text + "',address='" + textBox10.Text + "',personname='" + textBox11.Text + "',cellno='" + textBox12.Text + "',detail='" + textBox13.Text + "',total='" + Convert.ToDouble(textBox14.Text) + "' where id='" + empid + "'";

                SqlCommand cmd = new SqlCommand(query, cn);
                cn.Open();
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record Updates Successfully.....");
                cn.Close();
                clear();
                // binddata();
                dataGridView2.DataSource = GetCurrentRecords(CurrentPageIndex, cn);
                button3.Visible = true;
                button4.Visible = false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            SqlCommand cmd;
            SqlCommand Command;
            SqlDataReader Reader;
            try
            {
                empid = Convert.ToInt32(dataGridView2.Rows[e.RowIndex].Cells["id"].Value);
                switch (e.ColumnIndex)
                {
                    case 9:
                        cn.Open();
                        Command = new SqlCommand("Select * from cardetail where id='" + empid + "'", cn);
                        Reader = Command.ExecuteReader();
                        if (Reader.HasRows)
                        {
                            if (Reader.Read())
                            {
                                textBox8.Text = Reader.GetValue(1).ToString();

                                textBox9.Text = Reader.GetValue(2).ToString();
                                textBox10.Text = Reader.GetValue(3).ToString();
                                textBox11.Text = Reader.GetValue(4).ToString();
                                textBox12.Text = Reader.GetValue(5).ToString();
                                textBox13.Text = Reader.GetValue(6).ToString();
                                textBox14.Text = Reader.GetValue(7).ToString();
                                button4.Visible = true;
                                button3.Visible = false;
                            }

                        }
                        cn.Close();
                        break;

                    case 10:
                        cn.Open();
                        cmd = new SqlCommand("delete from cardetail where id = '" + empid + "'", cn);
                        cmd.ExecuteNonQuery();
                        cn.Close();
                        MessageBox.Show("Deleted Successfully.....");
                        // binddata();
                        dataGridView2.DataSource = GetCurrentRecords(CurrentPageIndex, cn);
                        break;
                    case 11:
                        cn.Open();

                        Command = new SqlCommand("Select * from cardetail where id='" + empid + "'", cn);
                        Reader = Command.ExecuteReader();
                        GenerateBillAndExport(Reader);
                        cn.Close();


                        break;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cn.Close();
            }
        }


        private void button7_Click(object sender, EventArgs e)
        {
            this.CurrentPageIndex = 1;
            this.dataGridView2.DataSource = GetCurrentRecords(this.CurrentPageIndex, cn);
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (this.CurrentPageIndex > 1)
            {
                this.CurrentPageIndex--;
                this.dataGridView2.DataSource =
            GetCurrentRecords(this.CurrentPageIndex, cn);
            }

        }

        private void button10_Click(object sender, EventArgs e)
        {
            this.CurrentPageIndex = TotalPage;
            this.dataGridView2.DataSource = GetCurrentRecords(this.CurrentPageIndex, cn);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (this.CurrentPageIndex <= this.TotalPage)
            {
                this.CurrentPageIndex++;
                this.dataGridView2.DataSource =
            GetCurrentRecords(this.CurrentPageIndex, cn);
            }

        }

        }





    }
}


0 comments:

Post a Comment