How can I change the default sort direction when clicking a column in a GridView?
How can I change the default sort direction when clicking a column in an ASP.NET GridView?
I would like it so that when a new column is clicked, it sorts in DESC order by default instead of ASC.
protected void OnGridViewSorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = RoomsGrid.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " +ConvertSortDirectionToSql(e.SortDirection);
RoomsGrid.DataSource = dataView;
RoomsGrid.DataBind();
}
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending: newSortDirection = "ASC"; break;
case Sort开发者_如何转开发Direction.Descending: newSortDirection = "DESC"; break;
}
return newSortDirection;
}
Here's an example of how it behaves now: http://www.venuefinder.com/venues/national_motorcycle_museum/V4204/meeting-rooms/
You can't change the GridView's default sort direction but since you are using a function to get the sort direction, you can do it manually as mentioned in the following link - http://www.mikepope.com/blog/DisplayBlog.aspx?permalink=1418
With reference to the code above, you can do the following to accomplish what you are asking:
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending: newSortDirection = "DESC"; break;
case SortDirection.Descending: newSortDirection = "ASC"; break;
}
return newSortDirection;
}
Hope this helps!
There's a nice MSDN article on this -- the sample it provides returns ASC as the default, but you could easily change that to DESC. Here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx#Y576
精彩评论