Sunday, April 3, 2011

GridView Paging using ASP.NET AJAX Slider Extender

As given in the ASP.NET AJAX Toolkit documentation “The Slider extender allows to upgrade an asp:TextBox to a graphical slider that allows the user to choose a numeric value from a finite range.” In this article, we will explore how to implement paging in an ASP.NET GridView using an ASP.NET AJAX SliderExtender.
Note: I am using Visual Studio 2008 and thereby utilizing the ASP.NET AJAX plumbing that comes along with it.
Let us get started with a Step-by-Step approach to do so. Viewers, who have prior experience in configuring the SqlDataSource, can jump directly to Step 5:
Step 1: Open VS 2008. Click File > New > Website. Choose ASP.NET Website from the list of installed template, choose target platform as .NET Framework 3.5, choose the desired language and enter the location where you would like to store the website on your FileSystem. I have created a folder called VS2008 Projects, so the location over here is C:\VS2008 Projects\ GridViewPaginUsingSliderExtender. After typing the location, click OK.
Step 2: Open Default.aspx. Switch to the Design mode of Default.aspx. Open the toolbox (Ctrl+Alt+X) > Data Tab > Drag and drop a SqlDataSource control on to the form. Click on the smart tag or right click SqlDataSource > Show Smart Tag > ‘Configure Data Source’ wizard. Click on ‘New Connection’ to open the ‘Add Connection’. Type your ‘Server Name’ and ‘Select a database Name’ to connect to. Over here, I have used (local) as the ‘ServerName’ and the database I am connecting to, is Northwind. Click on ‘Test Connection’ to make sure that there are no errors while connecting to the server. Click Ok.
Step 3: In the ‘Configure Data Source’, click ‘Next’. An option will be displayed to save the connection string to the configuration file. Select the checkbox ‘Yes, save this connection as:’, type a name for the connectionstring ‘NorthwindConnectionString’ and click Next.
Step 4: In the ‘Configure Select Statement’ > select ‘Specify Columns from Tables or Views’ radiobutton > Select ‘Alphabetical list of products’ View in the Name and choose ProductID, ProductName, QuantityPerUnit, UnitPrice, UnitsInStock and CategoryName. Click Next > ‘Test Query’ to preview data > click Finish. The wizard adds a SqlDataSource control to the page as shown below.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
    SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [CategoryName] FROM [Alphabetical list of products]">
asp:SqlDataSource>
 
If you check your web.config, the connection string is added as shown below:
<connectionStrings>
      <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
connectionStrings>
Step 5: Now add a control to the page and then an . Inside the , add a GridView(GridView1) control, set the data source property of the GridView to the 'SqlDataSource1' and ‘AutoGenerateColumns’ property to false. After defining the columns on the GridView, the markup will look similar to the following:
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
asp:ScriptManager>
<asp:UpdatePanel ID="UpdPanel1" runat="server">
<ContentTemplate>
 
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" AutoGenerateColumns="false"
DataKeyNames="ProductID" DataSourceID="SqlDataSource1"
    <Columns>
    <asp:BoundField DataField="ProductName" HeaderText="ProductName" ReadOnly="true" SortExpression="ProductName" />
    <asp:BoundField DataField="QuantityPerUnit" HeaderText="Qty" ReadOnly="true" SortExpression="QuantityPerUnit" />
    <asp:BoundField DataField="UnitPrice" HeaderText="PricePerUnit" ReadOnly="true" SortExpression="UnitPrice" />
    <asp:BoundField DataField="UnitsInStock" HeaderText="StockQty" ReadOnly="true" SortExpression="UnitsInStock" />
    <asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="true" SortExpression="CategoryName" />
    Columns>
asp:GridView>
 
ContentTemplate>
asp:UpdatePanel>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [CategoryName] FROM [Alphabetical list of products]">
asp:SqlDataSource>
 
div>
form>
body>
I have also added some css to enhance the UI of the GridView
<head runat="server">
<title>How to page a GridView Using an ASP.NET AJAX Slider Extendertitle>
<style type="text/css">
body
{
font: normal 11px auto "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;   
background-color: #ffffff;
color: #4f6b72;      
}
 
th {
font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #4f6b72;
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
border-top: 1px solid #C1DAD7;
letter-spacing: 2px;
text-transform: uppercase;
text-align: left;
padding: 6px 6px 6px 12px;
background: #D5EDEF;
}
 
td {
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
background: #fff;
padding: 6px 6px 6px 12px;
color: #4f6b72;
}
 
td.alt
{
background: #F5FAFA;
color: #797268;
}
 
td.boldtd
{
font: bold 13px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
background: #D5EDEF;
color: #797268;
}
style>
head>
Step 6: Now declare a inside the GridView and add a SliderExtender(ajaxSlider) from the toolbox (ASP.NET AJAX toolkit), a TextBox(txtSlide) and a Label(lblPage) control. Bind the ‘Text’ property of the ‘txtSlide’ using an expression. The lblPage will display the status of the current page as the user uses the Slider to do paging. The binding expressions will look similar to the ones shown below:
    Columns>
    <PagerTemplate>
    <asp:TextBox ID="txtSlide" runat="server" Text='<%# GridView1.PageIndex + 1 %>'  AutoPostBack="true" OnTextChanged="txtSlide_Changed"/>              
    <cc1:SliderExtender ID="ajaxSlider" runat="server"
    TargetControlID="txtSlide"    Orientation="Horizontal"                                    
    />
    <asp:Label ID="lblPage" runat="server" Text='<%# "Page " + (GridView1.PageIndex + 1) + " of " + GridView1.PageCount %>' />
    PagerTemplate>
asp:GridView>
The SliderExtender uses its ‘TargetControlID’ ‘txtSlide’ to store its position state. We will add code to the ‘txtSlide_Changed’ event handler in just a moment.
VB.NET users should replace ‘+’ with ‘&’
 <asp:Label ID="lblPage" runat="server" Text='<%# "Page " & (GridView1.PageIndex + 1) & " of " & GridView1.PageCount %>' />
 
Step 7: The last step is to set the SliderExtender properties in the ‘GridView_DataBound’ event and set the GridView PageIndex programmatically in the ‘txtSlide_Changed’ event.
Add the GridView_DataBound event handler
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" AutoGenerateColumns="false"
DataKeyNames="ProductID" DataSourceID="SqlDataSource1"
OnDataBound="GridView1_DataBound">
and in the codebehind, write the following code:
C#
protected void txtSlide_Changed(object sender, EventArgs e)
{
    TextBox txtCurrentPage = sender as TextBox;
    GridViewRow rowPager = GridView1.BottomPagerRow;
    TextBox txtSliderExt = (TextBox)rowPager.Cells[0].FindControl("txtSlide");
    GridView1.PageIndex = Int32.Parse(txtSliderExt.Text) - 1;       
}
 
protected void GridView1_DataBound(object sender, EventArgs e)
{
    GridViewRow rowPager = GridView1.BottomPagerRow;
    SliderExtender slide = (SliderExtender)rowPager.Cells[0].FindControl("ajaxSlider");
    slide.Minimum = 1;
    slide.Maximum = GridView1.PageCount;
    slide.Steps = GridView1.PageCount;
}
VB.NET
Protected Sub txtSlide_Changed(ByVal sender As Object, ByVal e As EventArgs)
      Dim txtCurrentPage As TextBox = TryCast(sender, TextBox)
      Dim rowPager As GridViewRow = GridView1.BottomPagerRow
      Dim txtSliderExt As TextBox = CType(rowPager.Cells(0).FindControl("txtSlide"), TextBox)
      GridView1.PageIndex = Int32.Parse(txtSliderExt.Text) - 1
End Sub
 
Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As EventArgs)
      Dim rowPager As GridViewRow = GridView1.BottomPagerRow
      Dim slide As SliderExtender = CType(rowPager.Cells(0).FindControl("ajaxSlider"), SliderExtender)
      slide.Minimum = 1
      slide.Maximum = GridView1.PageCount
      slide.Steps = GridView1.PageCount
End Sub
In the txtSlide_Changed event, the code first uses the ‘Find()’ method of the GridViewRow cells to find the txtSlide control. The ‘PageIndex’ of the GridView is then set to the value of the txtSlide.
The GridView_DataBound sets various properties on the SliderExtender. The slide.Maximum is the maximum value for the slider extender control position; in our case is the GridView.PageCount. The slide.Minimum is the minimum value for the slider control position.  The Steps property represents the number of discrete values in the Slider.
Note 1: Instead of setting the values in the GridView_DataBound event, you can also set the properties directly in the SliderExtender as shown by Vince Xu of the ASP.NET Forums
<cc1:SliderExtender ID="ajaxSlider" runat="server"
    TargetControlID="txtSlide"                           
    Orientation="Horizontal"
    Minimum="1"
    Steps='<%# GridView1.PageCount %>'
    Maximum='<%# ((GridView)Container.NamingContainer).PageCount %>'                                   
    />
Note 2: If you are wondering why the paging occurs only on MouseUp, then this is due to the ‘RaiseChangeOnlyOnMouseUp’ property of the SliderExtender. It’s a good practice to set the value of this property to true to avoid async postbacks to occur each time the slider value changes.
Run the application and you can now perform pagination using the ASP.NET AJAX SliderExtender control as shown below:
Grid View Slider
If you plan to implement paging using a SliderExtender in a ListView instead of a GridView, check out Matt Berseth’s article Data Navigation with the ListView, DataPager and SliderExtender Controls. I hope this article was useful and I thank you for viewing it. The source code of the article can be downloaded from here.

No comments:

Popular Posts