Friday, 19 October 2012

sorting in gridview in asp.net c#

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" onsorting="GridView1_Sorting">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
        <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
    </Columns>
</asp:GridView>
---------------------------------------------
The GridView Fields, for which data sorting functionality is needed, must define "SortExpression" property. Essentially SortExpression is the name of DataColumn in DataView.
Now populate a DataTable (to be bound with GridView) with the desired data. Then write a DataBindGrid function that is used to bind GridView to this DataTable. Below is code:

private void DataBindGrid(string sortExpr, string sortOrder)
{
    // GetDataTable returns a filled table
    DataTable dt = GetDataTable("sql query string");
    // any check to validate dt
    if (dt != null)
    {
        DataView dv = dt.DefaultView;
        if (sortExpr != string.Empty)
            dv.Sort = sortExpr + " " + sortOrder;           
        this.GridView1.DataSource = dv;
        this.GridView1.DataBind();
    }
    else
    {
        this.GridView1.DataSource = null;
        this.GridView1.DataBind();
    }
}
--------------------------------------------------
Reason behind is you have to call this function twice (i.e. in page load event and in GridView1_Sorting event).
Rate this Article When the page loads for the first time, simply clear the ViewState and load GridView Data According to sql query. Bellow is the sample code:
protected void Page_Load(object sender, EventArgs e)
{  
    if (!Page.IsPostBack)
    {
        // Set the sortingOrder property to ""
        ViewState["sortingOrder"] = string.Empty;
        DataBindGrid("", "");
    }
}
   
----------------------------------------------------------
When the user hit the header text link, following code should fire up:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    DataBindGrid(e.SortExpression, sortingOrder);
}
---------------------------------------------------------------
Below is the 'Property Backed ViewState' code
public string sortingOrder
{
    get
    {
        if(ViewState["sortingOrder"].ToString() == "desc")
            ViewState["sortingOrder"] = "asc";
        else
            ViewState["sortingOrder"] = "desc";
        return ViewState["sortingOrder"].ToString();
    }
    set
    {
        ViewState["sortingOrder"] = value;
    }
}

1 comment: