Creating Custom Paging for Datalist control



I have seen many article for DataList custom paging, every one showing paging in the DataList when the image is coming from a database. My requirement was for paging in a DataList when the image is coming from a folder.

This article demonstrates how to create custom paging for a DataList control when the image is coming from a folder.

Step 1:

Design a Form; drag a DataList Control from the toolbox. Set the Repeated Column property and design the DataList control as you require. Add link buttons for next, prev, first and last images.

<asp:DataList ID="DataList1" runat="server" RepeatColumns="4" BackColor="White"
            BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
            CellPadding="3"  ForeColor="Black"
            Width="100% onselectedindexchanged="DataList1_SelectedIndexChanged">
           <FooterStyle BackColor="#CCCCCC" />
                   <SelectedItemStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                    <HeaderTemplate>

                         <span class="style2">Image Gallary</span>
            </HeaderTemplate>

                <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                  <ItemTemplate>

                  <asp:ImageButton Width="105px" ID="Image1" runat="server"  BorderStyle="Solid" ImageUrl='<%# Bind("Name", "~/[foldername]/{0}") %>'
                 CommandName="Image" CommandArgument='<%# Bind("Name") %>' Height="94px"  />
                      <br />
                      <asp:Label ID="lblImg" Text='<%# Bind("Name") %>'    runat="server" Visible="false" />
                      <br />

                  </ItemTemplate>

                      <FooterStyle BackColor="White" ForeColor="#333333" />
                      <ItemStyle BorderColor="Silver" BorderStyle="Dotted" BorderWidth="1px" HorizontalAlign="Center"
                          VerticalAlign="Bottom" BackColor="White" ForeColor="#333333" />
      </asp:DataList>

      <asp:LinkButton ID="btnNext" runat="server" CausesValidation="False" onclick="btnNext_Click">Next &gt;</asp:LinkButton>
&nbsp; <asp:LinkButton ID="btnFirst" runat="server" CausesValidation="False"
                        onclick="btnFirst_Click">&lt;&lt; First
                    </asp:LinkButton>
&nbsp;<asp:LinkButton ID="btnPrev" runat="server" CausesValidation="False" onclick="btnPrev_Click">&lt;
                    Prev</asp:LinkButton>
&nbsp; <asp:LinkButton ID="btnLast" runat="server" CausesValidation="False" onclick="btnLast_Click">Last
                    &gt;&gt;</asp:LinkButton>

Step 2:

Write this following code...

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Gallary : System.Web.UI.Page
{
    int cnt; //count the total records
    int cntitem=0;//for counting item in list
    decimal last1; // access the last record
    PagedDataSource pagedData = new PagedDataSource();
    protected void Page_Load(object sender, EventArgs e)
    {       
            if (!IsPostBack)
            {

                BindImage();

            }
   }

        private ArrayList ListImages()
       {
           cntitem = 0;

        DirectoryInfo dir = new DirectoryInfo(MapPath("~/ThumbnailImage"));
          FileInfo[] file = dir.GetFiles();
          ArrayList list = new ArrayList();
          foreach (FileInfo file2 in file)
           {
             if (file2.Extension == ".jpg" || file2.Extension == ".jpeg" || file2.Extension == ".gif" || file2.Extension == ".png")
              {
                list.Add(file2);
              cntitem++;
              }
           }
        Session["cnt"] = cntitem;
        return list;
       } 

       private void doPaging()
       {

           // set the RepeatColumn property 2 of the Datalist control
           pagedData.DataSource = ListImages();//will fetch the records from getTheData() method
           //and store in pagedDataSource
           pagedData.AllowPaging = true;

           pagedData.PageSize = 8;
           //will display the 2 records at time in row and coulmn wise
           cnt = Convert.ToInt32(Session["cnt"]);
           //total record or you can use here viewstate
           last1 = cnt / pagedData.PageSize;
           last1 = Convert.ToDecimal(Math.Ceiling(last1));
           // to find the last record will change 9/2=4.5 into 5

           try
           {
               pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString["Page"].ToString());
           }
           catch (Exception ex)
           {
               pagedData.CurrentPageIndex = 0;
           }
           //place four buttons and name btnprev,btnfirst,last and btnnext
           btnPrev.Visible = (!pagedData.IsFirstPage);
           btnFirst.Visible = (!pagedData.IsFirstPage);

           btnNext.Visible = (!pagedData.IsLastPage);
           btnLast.Visible = (!pagedData.IsLastPage);

           DataList1.DataSource = pagedData;
           DataList1.DataBind();

       }

       protected void btnNext_Click(object sender, EventArgs e)
       {
           doPaging(); // will call the dopaging method
           Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (pagedData.CurrentPageIndex + 1).ToString());

       }
       protected void btnFirst_Click(object sender, EventArgs e)
       {
           doPaging();
           Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (pagedData.CurrentPageIndex == 1).ToString());
       }
       protected void btnPrev_Click(object sender, EventArgs e)
       {
           doPaging();
           Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (pagedData.CurrentPageIndex - 1).ToString());

       }
       protected void btnLast_Click(object sender, EventArgs e)
       {
           doPaging();
           Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (last1-1).ToString());
       }
       protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
       {
           DataList1.EditItemIndex = -1;
           doPaging();

       }
       void BindImage()
       {
           DataList1.DataSource = ListImages();
           DataList1.DataBind();
           doPaging();
       }

Step 3: Run your website………………….

Up Next
    Ebook Download
    View all
    Learn
    View all