Click here to Skip to main content
15,880,543 members
Articles / Programming Languages / C# 3.5
Tip/Trick

Listview Paging in C#

Rate me:
Please Sign up or sign in to vote.
4.60/5 (4 votes)
31 Jan 2013CPOL3 min read 53.2K   3K   8   7
Listview Paging Feature to split the records of the listview in sevaral pages.

Introduction

In Microsoft Visual C#, windows Forms application Project, there is a control for loading data’s and values like a spreadsheet that called as “Listview”.

Most of the peoples like to split the data’s into pages. Because more data’s in single page is very difficult to read. So they like to separate the data’s into several pages.

Background

The Listiview Paging Applications are already developed. But the Logic to implement feature are very difficult in existing code. So I find the new alternate way to implement this code.

 

The following logic program is developed by me. And It clearly gives an idea for the programmer to how to implement the listview paging.  

Code for Getting Sample Listiview Index Generation for Listiview Paging Feature:  

C#
using System;
namespace sample
{
    class test
    {
        static void Main(String[] args)
        {
            int TotalRec, NRPP;
            int TotalPages = 0;
            String p;
            System.Console.WriteLine("Enter Total Records");
            TotalRec = Convert.ToInt32(System.Console.ReadLine());
            //Getting value to set number records are shown in the page. 
            System.Console.WriteLine("Enter No. of Records Per Page");
            NRPP = Convert.ToInt32(System.Console.ReadLine());
            //calculating Total Pages
            TotalPages = TotalRec / NRPP;
            if (TotalRec % NRPP > 0)
                TotalPages++;
            System.Console.WriteLine("The Total Pages:{0}", TotalPages);
            //Creating Page Indexes
            int i, j;
            for (int k = 1; k <= TotalPages; k++)
            {
                System.Console.WriteLine("\n\n Page No:{0} \n", k);
                i = (k - 1) * NRPP;
                int start = i;
                int end = 0;
                j = k * NRPP;
                for (; i < j; i++)
                {
                    if (i >= TotalRec)
                    {
                        break;
                    }
                    System.Console.WriteLine("Record Index:{0}", i);
                    end = i;
                }
                System.Console.WriteLine("Records Showing From {0} to {1}", (start + 1), (end + 1));
                System.Console.WriteLine("*****End of Page***** \n");
                p = System.Console.ReadLine();
            }
        }
    }
}  

Using the code 

Form Design:  

Image 1

I have used 4 command buttons as a page navigator. And I put one numeric up and down control to change how many records should shown on the listview.  I Used two panels for holding navigator buttons and  holding numerical up and down control. 

Imported Namespace: 

C#
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.OleDb; 

 I have used only one form to implement this feature.

Public Variable Class: 

C#
public class LsvPageGlobVar
    {
        public static string ConStr;
        public static DataTable sqlDataTable = new DataTable();
        public static int TotalRec; //Variable for getting Total Records of the Table
        public static int NRPP; //Variable for Setting the Number of Recrods per listiview page
        public static int Page; //List View Page for Navigate or move
        public static int TotalPages; //Varibale for Counting Total Pages.
        public static int RecStart; //Variable for Getting Every Page Starting Record Index
        public static int RecEnd; //Variable for Getting Every Page End Record Index
    }  

These variables are holding shared values of form.

Public Method Class: 

I have created the following public class to create static methods to access the function in any other class.  

public class LsvPageFunc 

Data Base Connection Method: 

The database  is using to connect the desired database by OleDbConnection

C#
public static bool DbConnection()
        {
            bool functionReturnValue = false;
            try
            {
                 LsvPageGlobVar.ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=../../Database.mdb";
                //LsvPageGlobVar.ConStr ="Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=|DataDirectory|\data.mdb";      
                
                OleDbConnection sqlCon = new OleDbConnection();
                sqlCon.ConnectionString = LsvPageGlobVar.ConStr;
                sqlCon.Open();
                functionReturnValue = true;
                sqlCon.Close();
            }
            catch (Exception ex)
            {
                functionReturnValue = false;
                MessageBox.Show("Error : " + ex.ToString());
            }
            return functionReturnValue;
        } 

Query Execution Method: 

The following code is used to execute the SQL Queries. The method that returns the data table. 

C#
public static DataTable ExecSQLQry(string SQLQuery)
       {
           try
           {
               OleDbConnection sqlCon = new OleDbConnection(LsvPageGlobVar.ConStr);
               OleDbDataAdapter sqlDA = new OleDbDataAdapter(SQLQuery, sqlCon);
               OleDbCommandBuilder sqlCB = new OleDbCommandBuilder(sqlDA);
               LsvPageGlobVar.sqlDataTable.Reset();
               sqlDA.Fill(LsvPageGlobVar.sqlDataTable);
           }
           catch (Exception ex)
           {
               MessageBox.Show("Error : " + ex.ToString());
           }
           return LsvPageGlobVar.sqlDataTable;
       }

For example. We can execute the query. 

Just like,

C#
DataTable dtTest = new DataTable();  
dtTest= ExecSQLQry("SELECT * FROM tbl_name"); 
List View Data Loader Method: 

The following code is main method to load the paging in Listview Control. 

C#
public static void FillLsvData(DataTable sqlData, ListView lvList, int imageID)
        {
            //Load the table data in the listview
            int i = 0;
            int j = 0;
            int m = 0;
            int xsize;
            

            lvList.Clear();
            // for Adding Column Names from the datatable

            LsvPageGlobVar.TotalRec = sqlData.Rows.Count;

            //try
            //{
                LsvPageGlobVar.TotalPages = LsvPageGlobVar.TotalRec / LsvPageGlobVar.NRPP;

                if (LsvPageGlobVar.TotalRec % LsvPageGlobVar.NRPP > 0)
                {
                    LsvPageGlobVar.TotalPages++;
                }
            //}

            //catch(DivideByZeroException e)
            //{
            //    MessageBox.Show("Error : " + e.ToString());
            //}
            

            for (i = 0; i <= sqlData.Columns.Count - 1; i++)
            {
                lvList.Columns.Add(sqlData.Columns[i].ColumnName);
            }

            //for adding records to the listview from datatable
            int l, k;
            
            l = (LsvPageGlobVar.Page - 1) * LsvPageGlobVar.NRPP;
            k = ((LsvPageGlobVar.Page) * LsvPageGlobVar.NRPP);
            
            LsvPageGlobVar.RecStart = l + 1;
            if (k > LsvPageGlobVar.TotalRec)
            {
                LsvPageGlobVar.RecEnd = LsvPageGlobVar.TotalRec;
            }
            else
            {
                LsvPageGlobVar.RecEnd = k;
            }

            for (; l < k; l++)
            {
                if (l >= LsvPageGlobVar.TotalRec)
                {
                    break;
                }

                lvList.Items.Add(sqlData.Rows[l][0].ToString(), imageID);
               
                for (j = 1; j <= sqlData.Columns.Count - 1; j++)
                {
                    if (!System.Convert.IsDBNull(sqlData.Rows[l][j]))
                    {
                        lvList.Items[m].SubItems.Add(sqlData.Rows[l][j].ToString());
                        
                    }
                    else
                    {
                        lvList.Items[m].SubItems.Add("");
                        
                    } 
                }
                m++;
            }


            //for rearrange the column size
            for (i = 0; i <= sqlData.Columns.Count - 1; i++)
            {
                xsize = lvList.Width / sqlData.Columns.Count - 8;

                if (xsize > 1450)
                {
                    lvList.Columns[i].Width = xsize;
                    lvList.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                }

                else
                {
                    lvList.Columns[i].Width = 2000;
                    lvList.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                }



            }
        } 

From the above the following section, is used to calculate how many pages are required for the total records.

C#
LsvPageGlobVar.TotalPages = LsvPageGlobVar.TotalRec / LsvPageGlobVar.NRPP;
                if (LsvPageGlobVar.TotalRec % LsvPageGlobVar.NRPP > 0)
                {
                    LsvPageGlobVar.TotalPages++; 

We easily get how many records in the datatable, by using sqlData.Rows.Count.

 And then main think is we need create a starting record index and ending record index. This is done by the following two statements.

C#
l = (LsvPageGlobVar.Page - 1) * LsvPageGlobVar.NRPP;
k = ((LsvPageGlobVar.Page) * LsvPageGlobVar.NRPP);   

We can use this method like following example:

C#
LsvPageFunc.FillLsvData(LsvPageFunc.ExecSQLQry("Select * from tbl_Employee"),lsvData,0); 

This section is completed about the public methods. Now we are going to see the form events. 


Form Events: 

 Form Loading Event: 

C#
private void frmLsvPage_Load(object sender, EventArgs e)
       {
           lsvData.Width = this.Width - 30;
           lsvData.Height = pnlNavigate.Top-100;
           pnlNRPP.Left = this.Width - pnlNRPP.Width-30;
           LsvPageGlobVar.NRPP = Convert.ToInt32(nudNRPP.Value);
           
           LsvPageFunc.DbConnection();
           LsvPageGlobVar.Page = 1;
           LsvPageFunc.FillLsvData(LsvPageFunc.ExecSQLQry("Select * from tbl_Employee"),lsvData,0);
           lblInfo.Text="Record Shown: " + LsvPageGlobVar.RecStart + " to "+LsvPageGlobVar.RecEnd+ "                      Page "+LsvPageGlobVar.Page+" of " + LsvPageGlobVar.TotalPages;
       } 

The Variable LsvPageGlobVar.Page = 1; is initiating with first page to show the records. LsvPageGlobVar.NRPP is the variable using to set how many of records are shown in the listview page. 

Form Resize Event: 

The form resize event is using control the form layout in runtime.

C#
private void frmLsvPage_Resize(object sender, EventArgs e)
       {
           lsvData.Width = this.Width - 30;
           lsvData.Height = pnlNavigate.Top - 100;
           pnlNRPP.Left = this.Width - pnlNRPP.Width - 30;
       } 

Navigation Button Events:

The following codes are using to navigate the listview pages.

Move Next Button Event: 
C#
private void btnNext_Click(object sender, EventArgs e)
       {
           if (LsvPageGlobVar.Page < LsvPageGlobVar.TotalPages)
           {
               LsvPageGlobVar.Page++;
           }
           LsvPageFunc.FillLsvData(LsvPageFunc.ExecSQLQry("Select * from tbl_Employee"), lsvData, 0);
           lblInfo.Text = "Record Shown: " + LsvPageGlobVar.RecStart + " to " + LsvPageGlobVar.RecEnd + "                      Page " + LsvPageGlobVar.Page + " of " + LsvPageGlobVar.TotalPages;
       } 

The lblInfo is the label control that show the current record number and current page number.

Move Previous Button Event: 

C#
private void btnPrev_Click(object sender, EventArgs e)
       {
           if (LsvPageGlobVar.Page > 1)
           {
               LsvPageGlobVar.Page--;
           }
           LsvPageFunc.FillLsvData(LsvPageFunc.ExecSQLQry("Select * from tbl_Employee"), lsvData, 0);
           lblInfo.Text = "Record Shown: " + LsvPageGlobVar.RecStart + " to " + LsvPageGlobVar.RecEnd + "                      Page " + LsvPageGlobVar.Page + " of " + LsvPageGlobVar.TotalPages;
       }  
Move First Button Event: 
C#
private void btnFirst_Click(object sender, EventArgs e)
       {
           LsvPageGlobVar.Page = 1;
           LsvPageFunc.FillLsvData(LsvPageFunc.ExecSQLQry("Select * from tbl_Employee"), lsvData, 0);
           lblInfo.Text = "Record Shown: " + LsvPageGlobVar.RecStart + " to " + LsvPageGlobVar.RecEnd + "                      Page " + LsvPageGlobVar.Page + " of " + LsvPageGlobVar.TotalPages;
       } 
Move Last Button Event: 
C#
private void btnLast_Click(object sender, EventArgs e)
       {
           LsvPageGlobVar.Page = LsvPageGlobVar.TotalPages;
           LsvPageFunc.FillLsvData(LsvPageFunc.ExecSQLQry("Select * from tbl_Employee"), lsvData, 0);
           lblInfo.Text = "Record Shown: " + LsvPageGlobVar.RecStart + " to " + LsvPageGlobVar.RecEnd + "                      Page " + LsvPageGlobVar.Page + " of " + LsvPageGlobVar.TotalPages;
       } 
Numeric up and Down Control:(optional) 

This is optional event. Because the control that produce the 0 value. The control values is moved to the total pages calculation. It is used as a divider. If the value is 0, the system that produce an error. So I put this event to handle the Zero Division Error. 

And the Main think I produce this code to change the on time record showing. 

private void nudNRPP_ValueChanged(object sender, EventArgs e)
      {
          if (nudNRPP.Value != 0)
          {
              LsvPageGlobVar.NRPP = Convert.ToInt32(nudNRPP.Value);
          }
          else
          {
              nudNRPP.Value = 1;
          }
          LsvPageFunc.FillLsvData(LsvPageFunc.ExecSQLQry("Select * from tbl_Employee"), lsvData, 0);
          lblInfo.Text = "Record Shown: " + LsvPageGlobVar.RecStart + " to " + LsvPageGlobVar.RecEnd + "                      Page " + LsvPageGlobVar.Page + " of " + LsvPageGlobVar.TotalPages;

      }

Output Screen: 

Here the different state of the application. 

Image 2

 Image 3 

Image 4

History 

 Furthermore updates are need to enhanced this article. 

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Azeal Groups
India India
Thinking Innovation. .. ...

Technologies: .NET, Java, PHP, Python, SQL, Android, HTML, .

Comments and Discussions

 
Suggestionsuggestion about formatting a column Pin
rojaldearintok21-Oct-14 3:09
rojaldearintok21-Oct-14 3:09 
GeneralRe: suggestion about formatting a column Pin
Anand Gunasekaran15-Nov-14 1:52
professionalAnand Gunasekaran15-Nov-14 1:52 
GeneralJumping to a page Pin
rojaldearintok3-Oct-14 0:55
rojaldearintok3-Oct-14 0:55 
SuggestionRe: Jumping to a page Pin
Anand Gunasekaran18-Oct-14 3:06
professionalAnand Gunasekaran18-Oct-14 3:06 
GeneralRe: Jumping to a page Pin
rojaldearintok21-Oct-14 3:05
rojaldearintok21-Oct-14 3:05 
GeneralMy vote of 4 Pin
Fred Flams1-Feb-13 2:13
Fred Flams1-Feb-13 2:13 
Good article.

I like the idea behind the paging for a ListView.
Actually this could go further down the road by packaging all this into a nice user control that could be reusable. To achieve that changes are needed: no hard coding of the SQL Query, adding support for various datasources such as: DataSet, DataTable, Lists of objects, XML DOM, ...

Also one enhancement you could add would be to cache the result of the SQL Query rather than running it on each page change and have a "Refresh" data button that would sync with the database.
GeneralRe: My vote of 4 Pin
Anand Gunasekaran2-Feb-13 0:38
professionalAnand Gunasekaran2-Feb-13 0:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.