我有一个自动生成列 false 的网格视图。我想在单击每个列标题时对网格视图进行排序。我的代码适用于自动生成列 true,但我希望它是真的。
我的代码:
Protected Sub grdWork_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdPWork.Sorting
If ViewState("SortDirection") = SortDirection.Ascending Then
ViewState("SortDirection") = SortDirection.Descending
SortTrackingGrid(e.SortExpression, " Desc")
Else
ViewState("SortDirection") = SortDirection.Ascending
SortTrackingGrid(e.SortExpression, " Asc")
End If
End Sub
Private Sub SortTrackingGrid(ByVal SortExpression As String, ByVal SortDirection As String)
Dim TrackingDt As New DataTable
TrackingDt = objWebService.BindPWork()
Dim Trackingdv As New DataView
Trackingdv = TrackingDt.DefaultView
'Sort the grid
Trackingdv.Sort = SortExpression + SortDirection
grdPWork.DataSource = Trackingdv
grdPWork.DataBind()
End Sub
以下是使用自动生成列 false 对网格视图进行排序的完整示例。
http://www.dotnetgallery.com/kb/resource12-How-to-implement-paging-and-sorting-in-aspnet-Gridview-control.aspx
基本上,您需要在 GridView 排序事件中使用 SortExpression。
protected void Sorting(object sender, GridViewSortEventArgs e)
{
string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
if (SortOrder[0] == e.SortExpression)
{
if (SortOrder[1] == "ASC")
{
ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
}
else
{
ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
}
}
else
{
ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
}
GridVwPagingSorting.DataSource = Getdata();
GridVwPagingSorting.DataBind();
}