自定义的排序方法了,今天学习到了如何用dataset搭配gridview的话,进行标题排序,现将其方法摘录如下:
首先,用一个方法将数据取出来,放到DATASET里去,如下代码
private DataSet GetData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}
然后,对gridview进行如下设置
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting">
</asp:GridView>
然后,其gridview_sorting的自定义过程如下,首先添加一个属性
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
GridViewSortDirection 是一个简单的属性,用viewstate保存每次排序的方向
而GridView1_Sorting的代码如下:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
在这里,首先得到用户点击要排序列的标题,然后判断当前gridviewsortdirection的属性值来判断,如果已经是升序的话,则设置GridViewSortDirection为降序,并调用一个sortgridview过程;否则默认是调用升序来排序;
而sortgridview方法如下:
private void SortGridView(string sortExpression,string direction)
{
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
在这里,接收两个参数,分别是sortExpression和direction,然后构成dataview进行排序,十分好理解