Introduction: In this article i
am going to explain How to implement or enable sorting in asp.net GridView records in
ascending or descending order by clicking on GridView's column header in Asp.net
both using C# and VB language. In previous article i explained How to Bind and implement search gridview records and Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView and WCF Service to bind,insert,edit,update,delete and Highlight gridview row on mouse over using CSS and Bind,upload,download,delete image files from the GridView and Display Serial Number automatically in GridView.
Implementation: Let's create an
asp.net application to check the sorting in action.
First of all create a DataBase in Sql server e.g." Books_DB" and create "BookDetails" table using the script below:
CREATE TABLE
[dbo].[BookDetails]
(
[ID] [int] IDENTITY(1,1) NOT
NULL,
[BookName] [nvarchar](max) NULL,
[Author] [nvarchar](max) NULL,
[Publisher] [nvarchar](max)
NULL,
[Price] [decimal](18, 2) NOT
NULL
)
- Add some records in the table
- Then in the web.config file create the connection string in <configuration> tag as:
<add name="conStr" connectionString="Data Source=lalit;Initial Catalog=Books_DB;Integrated
Security=True"/>
</connectionStrings>
Note: Replace the Data Source and
Initial catalog as per your application.
- In the <body> tag of design page (.aspx) place a GridView control and configure it as:
<div>
<fieldset style="width:310px;">
<legend>Soring in Asp.net Gridview</legend>
<asp:GridView ID="grdBookDetails"
runat="server"
AutoGenerateColumns="False" AllowSorting="true"
onsorting="grdBookDetails_Sorting">
<Columns>
<asp:TemplateField HeaderText="Book
Name" SortExpression="BookName">
<ItemTemplate>
<asp:Label ID="lblBookName"
Text='<%#Eval("BookName")%>' runat="server"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Author"
SortExpression="Author">
<ItemTemplate>
<asp:Label ID="lblAuthor"
Text='<%#Eval("Author")%>' runat="server"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Publisher"
SortExpression="Publisher">
<ItemTemplate>
<asp:Label ID="lblPublisher"
Text='<%#Eval("Publisher")%>' runat="server"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price"
SortExpression="Price">
<ItemTemplate>
<asp:Label ID="lblPrice"
Text='<%#Eval("Price")%>' runat="server"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</fieldset>
</div>
C#.Net code to implement sorting
in GridView
- In the code behind file (.aspx.cs) first include the following namespaces:
using System.Data.SqlClient;
using System.Configuration;
then write the code as:
DataTable dt = new DataTable();
protected void
Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["sortOrder"] = "";
BindGridView("", "");
}
}
private void
BindGridView(string sortExp, string sortDir)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
SqlCommand cmd = new
SqlCommand("select
* from BookDetails", con);
SqlDataAdapter adp = new
SqlDataAdapter(cmd);
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
DataView dv = new DataView();
dv = dt.DefaultView;
if (sortExp != string.Empty)
{
dv.Sort = string.Format("{0} {1}", sortExp, sortDir);
}
grdBookDetails.DataSource = dv;
grdBookDetails.DataBind();
}
}
public string
sortOrder
{
get
{
if (ViewState["sortOrder"].ToString()
== "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}
return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}
protected void
grdBookDetails_Sorting(object sender, GridViewSortEventArgs e)
{
BindGridView(e.SortExpression, sortOrder);
}
VB.Net code to implement sorting
in GridView
- Design the page as shown in HTML Source as mentioned above but remove onsorting="grdBookDetails_Sorting" from the GridView source code.
- Then in code behind file(.aspx.vb) first include the following namespaces :
Imports System.Data.SqlClient
Imports System.Configuration
Then write the code as:
Dim dt As New DataTable
Protected Sub
Page_Load(sender As Object,
e As System.EventArgs)
Handles Me.Load
If Not
Page.IsPostBack Then
ViewState("sortOrder") = ""
BindGridView("", "")
End If
End Sub
Private Sub
BindGridView(sortExp As String, sortDir As String)
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
Dim cmd As New SqlCommand("select * from BookDetails", con)
Dim adp As New SqlDataAdapter(cmd)
adp.Fill(dt)
If dt.Rows.Count > 0 Then
Dim dv As
New DataView()
dv = dt.DefaultView
If sortExp <> String.Empty Then
dv.Sort = String.Format("{0} {1}", sortExp, sortDir)
End If
grdBookDetails.DataSource = dv
grdBookDetails.DataBind()
End If
End Sub
Public Property
sortOrder() As String
Get
If ViewState("sortOrder").ToString()
= "desc" Then
ViewState("sortOrder") = "asc"
Else
ViewState("sortOrder") = "desc"
End If
Return ViewState("sortOrder").ToString()
End Get
Set(value As String)
ViewState("sortOrder") =
value
End Set
End Property
Protected Sub
grdBookDetails_Sorting(sender As Object, e As
System.Web.UI.WebControls.GridViewSortEventArgs)
Handles grdBookDetails.Sorting
BindGridView(e.SortExpression, sortOrder)
End Sub
Now over to you:
" I hope you have got the way to sort the records in gridview and
If you like my work; you can appreciate by leaving your comments, hitting
Facebook like button, following on Google+, Twitter, Linked in and Pinterest,
stumbling my posts on stumble upon and subscribing for receiving free updates
directly to your inbox . Stay tuned and stay connected for more technical
updates."
4 comments
Click here for commentsNice Post Sir ....
ReplyThanks a lot for your feedback..stay connected and keep reading for more useful updates like this..:)
ReplyThanks! It helped me nicely.
ReplyHello ..i am glad you found this article helpful..stay connected and keep reading..:)
ReplyIf you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..