Did you know you can use jQuery for Sorting GridView asynchronously so that sorting takes place and also no page postback happens. This sorting technique with jQuery has the following advantages:
The below video shows the Sorting of the GridView taking place. Note that there is no page postback and also there is a loading image showing up during asynchronous operations:
In your ASP.NET Web Forms Project, create 2 new pages result.aspx and index.html.
In result.aspx add a GridView:
<asp:GridView ID="gridView" runat="server"></asp:GridView>
Next, go to the result.aspx.cs page and bind the GridView from data which is fetched from a database table:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
void BindGridView()
{
string colName = Request.Form["col"];
string sortOrder = Request.Form["order"];
string query = "";
if (sortOrder == null)
query = "SELECT PRODUCTNAME,QUANTITYPERUNIT,UNITPRICE,UNITSINSTOCK FROM PRODUCTS";
else if (sortOrder == "DESC")
query = "SELECT PRODUCTNAME,QUANTITYPERUNIT,UNITPRICE,UNITSINSTOCK FROM PRODUCTS ORDER BY " + colName + " " + sortOrder;
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataTable dataTable = new DataTable();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.Connection = conn;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = cmd;
try
{
sqlDataAdapter.Fill(dataTable);
gridView.DataSource = dataTable;
gridView.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
}
}
Explanation: On page load event we are binding the GridView by calling the BindGridView() C# function. In this function, we fetch the 2 values from Request.Form
method like:
string colName = Request.Form["col"];
string sortOrder = Request.Form["order"];
These 2 values ‘col’ & ‘order’ will be sent from jQuery code in the ‘index.html’ page. Based on these 2 values we will be doing the sorting of GridView.
Now see the below if condition:
if (sortOrder == null)
query = "SELECT PRODUCTNAME,QUANTITYPERUNIT,UNITPRICE,UNITSINSTOCK FROM PRODUCTS";
else if (sortOrder == "DESC")
query = "SELECT PRODUCTNAME,QUANTITYPERUNIT,UNITPRICE,UNITSINSTOCK FROM PRODUCTS ORDER BY " + colName + " " + sortOrder;
We check if the sortOrder is not passed from index.html (i.e. it is null) then we get all the Products from the Products table and there is no ‘order by’ clause applied.
Lastly, if the sortOrder is passed (so that it is not null) then we apply the “order by” clause to the SQL query like:
query = "SELECT PRODUCTNAME,QUANTITYPERUNIT,UNITPRICE,UNITSINSTOCK FROM PRODUCTS ORDER BY " + colName + " " + sortOrder;
In index.html page add the following HTML code:
<div class="imageDiv">
<img src="loading.gif" />
</div>
<div id="sortDetail"></div>
<div id="gridViewDiv"></div>
<input type="hidden" id="clickedColumn" />
<input type="hidden" id="sortOrder" />
The imageDiv contains a loading image that will be used to specify users that the AJAX request is going on currently.
The sortDetail div will shown the current sorting order applied on a column of the GridView.
The gridViewDiv will show the GridView data fetched from result.aspx page using AJAX.
Two hidden input controls that will hold the value of the:
See the below 2 lines of codes:
<input type="hidden" id="clickedColumn" />
<input type="hidden" id="sortOrder" />
Now apply the following jQuery code to your index.html page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#gridViewDiv").load("result.aspx #gridView", function (response, status, xhr) {
if (status == "error")
$("#gridViewDiv").html("Error: " + xhr.status + ": " + xhr.statusText);
});
$("#gridViewDiv").on("click", "th", function () {
GetOrder($(this).text());
$("#gridViewDiv").load("result.aspx #gridView", { "col": $("#clickedColumn").val(), "order": $("#sortOrder").val() }, function (response, status, xhr) {
if (status == "error")
$("#gridViewDiv").html("Error: " + xhr.status + ": " + xhr.statusText);
});
$("#sortDetail").html("column: " + $("#clickedColumn").val() + "<br/>" + "sorting: " + $("#sortOrder").val());
});
function GetOrder(column) {
if (($("#clickedColumn").val() == "") || ($("#clickedColumn").val() != column)) {
$("#sortOrder").val("ASC");
}
else if ($("#clickedColumn").val() == column) {
if ($("#sortOrder").val() == "ASC")
$("#sortOrder").val("DESC");
else if ($("#sortOrder").val() == "DESC")
$("#sortOrder").val("ASC");
}
$("#clickedColumn").val(column);
}
$(document).ajaxStart(function () {
$("img").show();
});
$(document).ajaxStop(function () {
$("img").hide();
});
});
</script>
Explanation: We have used jQuery Load method to get the GridView from result.aspx page like this:
$("#gridViewDiv").load("result.aspx #gridView", function (response, status, xhr) {
if (status == "error")
$("#gridViewDiv").html("Error: " + xhr.status + ": " + xhr.statusText);
});
Here we haven’t sent any values from the load method. So the GridView will bind records from ‘Products’ table without applying ‘Order By’ clause.
When any of the GridView’s header column is clicked then the below click event will fire, and it will send the ‘col’ and ‘order’ to the result.aspx page.
$("#gridViewDiv").on("click", "th", function () {
GetOrder($(this).text());
$("#gridViewDiv").load("result.aspx #gridView", { "col": $("#clickedColumn").val(), "order": $("#sortOrder").val() }, function (response, status, xhr) {
if (status == "error")
$("#gridViewDiv").html("Error: " + xhr.status + ": " + xhr.statusText);
});
$("#sortDetail").html("column: " + $("#clickedColumn").val() + "<br/>" + "sorting: " + $("#sortOrder").val());
});
So now the GridView will bind records from Products table by applying ‘Order By’ clause, and this way sorting will be done.
The GetOrder() method stores the ‘clicked header column name’ and ‘sort order’ to be applied, in the 2 hidden input controls:
function GetOrder(column) {
if (($("#clickedColumn").val() == "") || ($("#clickedColumn").val() != column)) {
$("#sortOrder").val("ASC");
}
else if ($("#clickedColumn").val() == column) {
if ($("#sortOrder").val() == "ASC")
$("#sortOrder").val("DESC");
else if ($("#sortOrder").val() == "DESC")
$("#sortOrder").val("ASC");
}
$("#clickedColumn").val(column);
}
<p>The below 2 method shows and hides the load image to tell user when the AJAX request is going on:</p>
$(document).ajaxStart(function () {
$("img").show();
});
$(document).ajaxStop(function () {
$("img").hide();
});
Run the ‘index.html’ page in the browser and you will see the GridView loaded from result.aspx page as shown below:
Now click the ‘productName’ column and you will see the GridView now sorts in ASCENDING manner.
Click the ‘productName’ column once more and you will see the GridView now sorts in DESCENDING manner.
Download the codes: