問題
使用 GridView做出排序效果
解決方法
.aspx
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False" Width="100%" AllowSorting="True" OnSorting="gvData_Sorting">.cs
<Columns>...</Columns>
</asp:GridView>
private static Hashtable ht;//定義暫存變數
private static Hashtable sort;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ht = null ?? new Hashtable();//初始化暫存變數
sort = null ?? new Hashtable();
DataTable dt = queryData();
ht[userid] = dt;//資料暫存於變數
gvData.DataSource = dt;
gvData.DataBind();
}
}
protected void gvData_Sorting(object sender, GridViewSortEventArgs e)
{
SetSortDirection((string)sort[userid]);//傳入排序資料變數
if (ht[userid] != null)
{
//Sort the data.
DataTable dt = (DataTable)ht[userid];//取出暫存變數
dt.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
gvData.DataSource = dt;
gvData.DataBind();
sort[userid] = _sortDirection;//排序資料暫存於變數
}
}
string _sortDirection;
protected void SetSortDirection(string sortDirection)
{
if (sortDirection == "ASC")
_sortDirection = "DESC";
else
_sortDirection = "ASC";
}
沒有留言:
張貼留言