Which Gridview property must be enabled to Sort rows?

 Posted by vishalneeraj-24503 on 12/10/2013 | Category: ASP.NET Interview questions | Views: 1295 | Points: 40

We have to set AllowSorting = "true" in Gridview definition.
Add Sortexpression="Column_Name" in Templatefield or in BoundField.
Then we can have Sorting functionality.

Suppose,we have a Gridview like below:-

<asp:GridView ID="grid_view_employee_details" runat="server" AllowSorting="true"

SortDirection and SortExpression are the properties we have to refer for Sorting purpose.

I am assuming that,Gridview has filled with data.
OnSorting event,we have to write code as:-

protected void grid_view_employee_details_OnSorting(object sender, GridViewSortEventArgs e)
DataTable dtGridData = ViewState["grdDataSource"] as DataTable;
DataView dvGridDataView = dtGridData.DefaultView;
string strSortOrder = "";
if (ViewState["SortOrder"]==null)
ViewState["SortOrder"] = "asc";
if (ViewState["SortOrder"].ToString() == "asc")
ViewState["SortOrder"] = "desc";
strSortOrder = "desc";
else if (ViewState["SortOrder"].ToString() == "desc")
ViewState["SortOrder"] = "asc";
strSortOrder = "asc";
dvGridDataView.Sort = e.SortExpression + " " + strSortOrder;
dtGridData = dvGridDataView.ToTable();

grid_view_employee_details.DataSource = dtGridData;

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response