ASP.NET Web Forms – Sorting GridView with jQuery Load method with no page postback

ASP.NET Web Forms – Sorting GridView with jQuery Load method with no page postback

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:

  1. The sorting takes place with just a few lines of codes.
  2. There is no code duplication as you can use call the same GridView from multiple pages with jQuery.
  3. You don’t need to add GridView sorting event in your .cs page since jQuery will take care the sorting task.
  4. There is no use of Update panel when performing sorting.
  5. 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:

    GridView Sorting jQuery load

    Project Details

    In your ASP.NET Web Forms Project, create 2 new pages result.aspx and index.html.

    Result.aspx

    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;
    Index.html

    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:

    1. Column name where sorting is to be applied.
    2. Sort order (ascending or descending) to be applied on the ‘order by’ clause.

    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();
    });

    Testing

    Run the ‘index.html’ page in the browser and you will see the GridView loaded from result.aspx page as shown below:

    Unsorted GridView Column

    Now click the ‘productName’ column and you will see the GridView now sorts in ASCENDING manner.

    Ascending Sorted GridView Column

    Click the ‘productName’ column once more and you will see the GridView now sorts in DESCENDING manner.

    Descending Sorted GridView Column

    Download the codes:

    Download

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate

Leave a Reply

Your email address will not be published. Required fields are marked *