In this article I will explain with an example, how to implement
AJAX Sorting in
GridView using UpdatePanel in
ASP.Net with C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The following
HTML Markup consists of:
ScriptManager - For enabling
AJAX functions.
UpdatePanel – For refreshing the Web Page partially.
ContentTemplate – Defining the content of the UpdatePanel control.
GridView – For displaying data.
Columns
The
GridView consists of
TemplateField columns.
TemplateField - The TemplateField column consists of ItemTemplate.
Events
The
GridView has been assigned with
OnPageIndexChanging event handlers.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="dvGrid" style="width:500px">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" AllowPaging="true"
AllowSorting="true" OnSorting="OnSorting" OnPageIndexChanging="OnPageIndexChanging"
PageSize="10">
<Columns>
<asp:TemplateField ItemStyle-Width="150px" HeaderText="Customer ID" SortExpression="CustomerID">
<ItemTemplate>
<%# Eval("CustomerID")%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" SortExpression="ContactName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Populating GridView from database
Inside the
Page Load event of the page, the
GridView is populated with records from the
Customers table of the
Northwind database.
The
SortDirection property is a
ViewState property which is used to save the Sort Direction of
GridView during
PostBacks.
Once the
DataTable is populated, it is converted into a DataView and then the
SortExpression and
SortDirection values are used to sort the data.
C#
private string SortDirection
{
get {return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; }
set { ViewState["SortDirection"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid(string sortExpression = null)
{
string sql = "SELECT CustomerId, ContactName, City, Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
if (sortExpression != null)
{
DataView dv = dt.AsDataView();
this.SortDirection = this.SortDirection =="ASC" ? "DESC" : "ASC";
dv.Sort = sortExpression + " " + this.SortDirection;
gvCustomers.DataSource = dv;
}
else
{
gvCustomers.DataSource = dt;
}
gvCustomers.DataBind();
}
}
}
}
}
VB.Net
Private Property SortDirection As String
Get
Return IIf(ViewState("SortDirection")IsNot Nothing, Convert.ToString(ViewState("SortDirection")), "ASC")
End Get
Set(value As String)
ViewState("SortDirection") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid(Optional sortExpression As String = Nothing)
Dim sql As String = "SELECT CustomerId, ContactName, City, Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(sql, con)
Using sda As New SqlDataAdapter()
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
If sortExpression IsNot Nothing Then
Dim dv As DataView = dt.AsDataView()
Me.SortDirection = If(Me.SortDirection ="ASC", "DESC", "ASC")
dv.Sort = sortExpression & " " & Me.SortDirection
gvCustomers.DataSource = dv
Else
gvCustomers.DataSource = dt
End If
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End Sub
Implementing Paging in GridView
Inside the
OnPageIndexChanging event handler, the
PageIndex property of the
GridView is set with the new
PageIndex and the
BindGrid method is called.
C#
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvCustomers.PageIndex = e.NewPageIndex;
this.BindGrid();
}
VB.Net
Protected Sub OnPageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gvCustomers.PageIndex = e.NewPageIndex
Me.BindGrid()
End Sub
Implementing Sorting in GridView
This event handler is executed when a Column is sorted in
GridView.
The value of the Sort Expression of the Column which was clicked is present inside the SortExpression property of the GridViewSortEventArgs object and it is passed as parameter to the BindGrid function.
C#
protected void OnSorting(object sender, GridViewSortEventArgs e)
{
this.BindGrid(e.SortExpression);
}
VB.Net
Protected Sub OnSorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
Me.BindGrid(e.SortExpression)
End Sub
Screenshot
Demo
Downloads