Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET GridView Sorting Implementation & Event Handling

Can someone share how to practically implement gridview sorting and handle that event if:

  1. The data is binded manually
  2. Gridview is built using template field that is pumped from code behind only (not from the markups)

I build my gridview solely from codebehind therefore I can't use the default method or solution.

Thank you

like image 681
rofans91 Avatar asked Feb 21 '23 23:02

rofans91


1 Answers

This might be what you are looking for:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    listBindByName(); //this would be your procedure to look for the data you want
    DataSet dsSortTable = GridView1.DataSource as DataSet;
    DataTable dtSortTable = dsSortTable.Tables[0];
    if (dtSortTable != null)
    {
        DataView dvSortedView = new DataView(dtSortTable);
        dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString();
        ViewState["sortExpression"] = e.SortExpression;
        GridView1.DataSource = dvSortedView;
        GridView1.DataBind();
    }
    UpdatePanel1.Update();
}

private string getSortDirectionString()
{
    if (ViewState["sortDirection"] == null)
    {
        ViewState["sortDirection"] = "ASC";
    }
    else
    {
        if (ViewState["sortDirection"].ToString() == "ASC")
        {
            ViewState["sortDirection"] = "DESC";
            return ViewState["sortDirection"].ToString();
        }
        if (ViewState["sortDirection"].ToString() == "DESC")
        {
            ViewState["sortDirection"] = "ASC";
            return ViewState["sortDirection"].ToString();
        }
    }
    return ViewState["sortDirection"].ToString();
}

This is an example of the TemplateField:

<asp:TemplateField HeaderText="Description" SortExpression="description">
    <ItemTemplate>
        <asp:Label Visible="true" runat="server" ID="descriptionLabel" Text='<%# bind("description")  %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtEditDescription" Width="100px" runat="server" Text='<%#Bind("description") %>' />
    </EditItemTemplate>
</asp:TemplateField>

By adding the SortExpression property the GridView header will become clickable. Make sure the sort expression attribute is the name of the field that you are binding through the sql query.

Hope this helps.

like image 92
aleafonso Avatar answered Mar 03 '23 06:03

aleafonso