Can anyone tell the function to sort the columns of a gridview in c# asp.net.
The databound to gridview is from datacontext created using linq. I wanted to click th
http://msdn.microsoft.com/en-us/library/ms745786.aspx
http://aspnet.4guysfromrolla.com/articles/012308-1.aspx
add:
AllowSorting="true"
to the <asp:GridView />
tag, that should do it
In Half Pseudocode for SQL Query
string Query= string.Empty;
string SortExpression = string.Empty;
// HDFSort is an HiddenField !!!
protected void SortCommand_OnClick(object sender, GridViewSortEventArgs e)
{
SortExpression = e.SortExpression;
Query = YourQuery + " ORDER BY "+SortExpression +" "+ HDFSort.Value ;
HDFSort.Value = HDFSort.Value== "ASC" ? "DESC" : "ASC";
RefreshGridView();
}
protected void RefreshGridView()
{
GridView1.DataSource = DBObject.GetData(Query);
GridView1.DataBind();
}
In the Properties Panel double Click on the Sorting Entry. A new Function will be created. In this Function write the Code to fill the Gridview. The only difference is to change the query based on GridViewSortEventArgs e
e.SortExpression
and
e.SortDirection allways Ascending :-(
I hope this very short Answer helps
There are 2 things you need to do to get this right.
Manually handle the Sorting event in the grid and use this helper I wrote to sort by SortExpression and SortDirection:
public static IQueryable<T> SortBy<T>(IQueryable<T> source, string sortExpression, SortDirection direction) {
if (source == null) {
throw new ArgumentNullException("source");
}
string methodName = "OrderBy";
if (direction == SortDirection.Descending) {
methodName += "Descending";
}
var paramExp = Expression.Parameter(typeof(T), String.Empty);
var propExp = Expression.PropertyOrField(paramExp, sortExpression);
// p => p.sortExpression
var sortLambda = Expression.Lambda(propExp, paramExp);
var methodCallExp = Expression.Call(
typeof(Queryable),
methodName,
new[] { typeof(T), propExp.Type },
source.Expression,
Expression.Quote(sortLambda)
);
return (IQueryable<T>)source.Provider.CreateQuery(methodCallExp);
}
db.Products.SortBy(e.SortExpression, e.SortDirection)
Check out my blog post on how to do this:
more information on sorting in a gridview can be found here: MSDN Gridview sorting the methodology used to get the data should not matter, you can use the same sorting.