C# 在代码隐藏中为 ASP.net 中的 GridView 创建排序的代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/704600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Code to create Sorting for a GridView in ASP.net in Code Behind?
提问by Etienne
This is my code code for the Page_Load Event
这是我的 Page_Load 事件代码
OdbcConnection myConnection;
DataSet dataSet = new DataSet();
OdbcDataAdapter adapter;
//making my connection
myConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings ["ODBC_ConnectionString"].ConnectionString);
adapter = new OdbcDataAdapter("SELECT * from Company", myConnection);
adapter.Fill(dataSet, "MyData");
GridView1.DataSource = dataSet;
Session["DataSource"] = dataSet;
GridView1.DataBind();
This is my code for the PageIndexChanging event and it all works fine.
这是我的 PageIndexChanging 事件代码,一切正常。
DataSet ds = new DataSet();
if (Session["DataSource"] != null)
ds = ((DataSet)Session["DataSource"]);
GridView1.DataSource = ds;
GridView1.PageIndex = e.NewPageIndex;
this.GridView1.DataBind();
Now what code do i need to create the Sorting event?
现在我需要什么代码来创建排序事件?
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
?????????????????????????
}
Etienne
艾蒂安
回答by SirDemon
You can filter and sort your dataset using:
您可以使用以下方法过滤和排序数据集:
ds.Tables[0].Select(filterExp, sortExp, etc...);
回答by aquinas
I usually do this:
我通常这样做:
public string SortField {
get {
return (string) ViewState["_sortField"];
}
set {
ViewState["_sortField"] = value;
}
}
public string SortDir {
get {
return (string) ViewState["_sortDir"];
}
set {
ViewState["_sortDir"] = value;
}
}
Put your code to do databinding into another Method because you have to call it during Sort, Paging, and when your page first loads. Call it DoDataBind() for example. Then you have in DoDataBind()
将用于数据绑定的代码放入另一个方法中,因为您必须在排序、分页和页面首次加载时调用它。例如,称其为 DoDataBind()。然后你在 DoDataBind()
DataTable dt = yourDataSet.Tables[0];
dt.DefaultView.Sort = SortField + " " + SortDir;
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
Then your event looks like this:
然后你的事件看起来像这样:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
if (e.SortExpression == SortField && SortDir != "desc") {
SortDir = "desc";
}
else {
SortDir = "asc";
}
SortField = e.SortExpression;
DoDataBind();
}
Then in your aspx page you'll need to specify what the SortExpression is. For example something like this:
然后在您的 aspx 页面中,您需要指定 SortExpression 是什么。例如这样的事情:
<asp:BoundField DataField="FIRSTNAME"
HeaderText="First Name" SortExpression="FIRSTNAME" />

