I am writing project which gets data from Data Acess Layer and show it in GridView. The problem is to allow sorting by column. When I click on head of columnt following occu
The GridView does not sort itself. You need to add some code for a GridView sorting event and wire it up.
First, you add the name of the OnSorting
event to the GridView
on the .aspx
page:
<asp:GridView ID="gridView" OnSorting="gridView_Sorting" runat="server" />
Then, you add that event in the code-behind. This example also handles changing the sort direction -- once the user has sorted, they may want to reverse the sort direction, and you have to keep track of that.
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gridView.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
gridView.DataSource = dataView;
gridView.DataBind();
}
}
You need to define a sort melhod, and implement it:
<asp:GridView ID="GridView1" **OnSorting="gridViewSorting"** runat="server" />
protected void gridViewSorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gridView.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = your sort expression
gridView.DataSource = dataView;
gridView.DataBind();
}
}