SIGN UP MEMBER LOGIN:    
ARTICLE

Creating Custom Paging for Datalist control

Posted by Ankit Nandekar Articles | ADO.NET in C# March 10, 2011
This article demonstrates how to create custom paging for a DataList control when the image is coming from a folder.
Reader Level:


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………………….

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor