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 <ScriptManager> control to the page and then an <UpdatePanel>. Inside the <UpdatePanel>, 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 Extender</title>
<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 <PagerTemplate> 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:
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn