Can someone share how to practically implement gridview sorting and handle that event if:
- The data is binded manually
- 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With