How To Ideas | How To Articles | How To Tutorials


0

How To Enable Sorting In Grid View


If you want to show data to user using Grid View and also wants user to sort data by just clicking header of the Grid view, then this article may be helpful for you. In this article, I will show you the easiest way using which you can enable Sorting in GridView while creating websites. We have to code in such a way that when user clicks on any column header then data in the grid view got sorted according to the data present in that column firstly in increasing order then in decreasing.

Instructions:

  1. Create a new website or open an existing one in Visual Studio.
  2. Add a GridView control to one of the pages in the website.
  3. Select the GridView Control and open its properties. If properties window is not there, then you can open it by hitting shortcut key “Ctrl + W, P” or by going to “View” menu and then “Properties Window”. You can open Properties window just by selecting Grid View then pressing F4.
  4. Change the value for AllowSorting from False to True. This property is set to False by default.
    image
  5. Now Open its events window by clicking the lightening icon in the properties window.
    image
  6. Now double click on the Sorting which will create a new method       protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
  7. Add the following lines of code in that event

    DataTable dt = Session["Table"] as DataTable;
    if (dt != null)
    {
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        GridView1.DataSource = Session["Table"];
        GridView1.DataBind();
    }

  8. Here we are calling GetSortDirection, which has the information regarding whether the sorting should be done in Ascending order or Descending. Code for that method is as follows

    private string GetSortDirection(string column)
    {
        string sortDirection = "ASC";

        string sortExpression = ViewState["SortExpression"] as string;

        if (sortExpression != null)
        {
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }
        ViewState["SortDirection"] = sortDirection;
        ViewState["SortExpression"] = column;

        return sortDirection;
    }

  9. Now, you will be having Sorting enabled in your GridView and working fine.

Incoming search terms:

  • c# code to sort the data in accending order (1)
  • gridview dynamically enable sorting (1)
Filed in: ASP.NET Tags: , , , , , , , , , , , , , ,

Leave a Reply

Submit Comment



© 5400 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.