有人能告诉我如何在c# asp.net中对gridview的列进行排序吗?
gridview绑定的数据来自使用linq创建的datacontext。我希望能够点击列标题来对数据进行排序。
谢谢!
要正确完成此操作,您需要执行以下两个步骤:
在网格中手动处理 Sorting 事件,并使用我编写的帮助程序按 SortExpression 和 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)
请按照我的博客文章中的说明进行操作。
string header = ((Binding)headerClicked.Column.DisplayMemberBinding).Path.Path;
MSDN上的代码只有在标题和列名完全相同时才能正常排序。 - Jared Harley添加:
AllowSorting="true"
加入 <asp:GridView />
标签,就可以了
<asp:LinqDataSource ID="dsMyDataSource" runat="server"
DataContextTypeName="MyDataContext"
TableName="MyTable"
AllowSort="true" />
然后在你的GridView中:
<asp:GridView ID="gvMyGridView" runat="server" DataSourceID="dsMyDataSource" ... />
在半伪代码中的SQL查询
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();
}