Showing posts with label sort data in gridview. Show all posts
Showing posts with label sort data in gridview. Show all posts

Friday, 18 April 2014

How to sort data in GridView in ASP.NET

In this article, i am going to give some overview on how to Sort the data when user click on Gridview Header Cell. While doing this, I developed a good piece of code which I do feel will help most of you in your development activity. 

Some Steps to enable Sorting :-
  1. Set AllowSorting="True" Property of GridView to enable sorting.
  2. Set SortExpression property of each column.
  3. Declare Sorting Event Name by just giving value in OnSorting in GridView.
aspx Page
<asp:GridView ID="gvOrders" Width="25%" runat="server" AutoGenerateColumns="False" AllowSorting="true" OnSorting="gvOrders_Sorting">
                  <Columns>
                      <asp:TemplateField HeaderText="Data Items" HeaderStyle-BackColor="Black">
                          <ItemTemplate>
                              <asp:Label ID="lblDataItem" runat="server" Text='<%# Container.DataItemIndex %>'></asp:Label>
                          </ItemTemplate>
                      </asp:TemplateField>
                      <asp:TemplateField HeaderText="Price" SortExpression="price">
                          <ItemTemplate>
                              <asp:Label ID="lblPrice" runat="server" Text='<%# Eval("price") %>' />
                          </ItemTemplate>
                      </asp:TemplateField>
                      <asp:TemplateField HeaderText="Quantity" SortExpression="quantity">
                          <ItemTemplate>
                              <asp:Label ID="lblQuantity" runat="server" Text='<%# Eval("quantity") %>' />
                          </ItemTemplate>
                      </asp:TemplateField>
                  </Columns>
 </asp:GridView>

aspx.cs Page
   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gvOrders.DataSource = bindData();
            gvOrders.DataBind();
        }
    }

    DataTable bindData()
    {
        string connectionString = "Server=localhost;Database=master;Trusted_Connection=true";
        SqlConnection myConnection = new SqlConnection(connectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT price, quantity FROM demo", myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds);
        return ds.Tables[0];
    }

    protected void gvOrders_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortingDirection = string.Empty;
        if (gridviewDirection == SortDirection.Ascending) // if ascending, make it descending
        {
            gridviewDirection = SortDirection.Descending;
            sortingDirection = "Desc";
        }
        else
        {
            gridviewDirection = SortDirection.Ascending; // if descending, make it ascending
            sortingDirection = "Asc";
        }

        DataView sortedView = new DataView(bindData()); // get gridview data and store it in dataview
        sortedView.Sort = e.SortExpression + " " + sortingDirection; // format(Column_Name [ASC|DESC])
        gvOrders.DataSource = sortedView;
        gvOrders.DataBind(); // bind gridview data after sorting in appropriate format
    }
Now here, I am storing direction in ViewState i.e.(Ascending or Descending). 


    public SortDirection gridviewDirection
    {
        get
        {
           if (ViewState["directionState"] == null)
           {
               ViewState["directionState"] = SortDirection.Ascending; // to set default value ascending
           }
           return (SortDirection)ViewState["directionState"];
        }

        set
        { ViewState["directionState"] = value; }
    }
To show all gridview rows in edit mode http://dotnetcodingcircle.blogspot.in/2014/04/show-all-gridview-rows-in-editmode-on.html


That’s it!!…..Happy Programming...