程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> ASP.NET GirdView學習之三 排序

ASP.NET GirdView學習之三 排序

編輯:關於ASP.NET

要先設置GridView的AllowSortring=true,這樣當點擊列標題的時候才能激發GridView的Sorting事件進行排序

1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11using System.Collections.Generic;
12
13public partial class GridViewSortingTest : System.Web.UI.Page
14{
15  protected void Page_Load(object sender, EventArgs e)
16  {
17    if (!IsPostBack)
18    {
19      ClientInfoAccessObj accessor = new ClientInfoAccessObj();
20      GridView1.DataSource = accessor.GetAllClients();//綁定所有客戶信息
21      GridView1.DataBind();
22    }
23  }
24  //按照客戶姓名進行排序比較
25  public int CompareByClientName(ClientInfo Client1, ClientInfo Client2)
26  {
27    return Client1.ClientName.CompareTo(Client2.ClientName);
28  }
29
30  //按照郵編和地址進行排序比較
31  public int CompareByPostCodeAndAddressStr(ClientInfo client1, ClientInfo client2)
32  {
33    int ret = client1.PostCode.CompareTo(client2.PostCode);
34    if (ret != 0)
35      return ret;
36    else//如果郵編一樣
37    {
38      return client1.AddressStr.CompareTo(client2.AddressStr);
39    }
40  }
41  //按照郵編進行排序比較
42  public int CompareByPostCode(ClientInfo client1, ClientInfo client2)
43  {
44    return client1.PostCode.CompareTo(client2.PostCode);
45  }
46  //正在排序的事件
47  protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
48  {
49    ClientInfoAccessObj accessor = new ClientInfoAccessObj();
50    List<ClientInfo> clients = accessor.GetAllClients();
51    switch (e.SortExpression)
52    {
53      case "ClientName":
54        clients.Sort(CompareByClientName);//參數是一個Comparison<T>類型的泛型委托的函數名
55        break;
56      case "MultiColumnSort":
57        clients.Sort(CompareByPostCodeAndAddressStr);
58        break;
59      case "PostCode":
60        clients.Sort(CompareByPostCode);
61        break;
62      default:
63        ClientScript.RegisterClientScriptBlock(this.GetType(), "InfoMsg", "alert('不支持對此字段進行排序');", true);
64        break;
65    }
66    GridView1.DataSource = clients;//綁定顯示數據
67    GridView1.DataBind();
68  }
69  protected void btnSortByName_Click(object sender, EventArgs e)
70  {
71    GridView1.Sort("ClientName", SortDirection.Ascending);//此事件執行完畢再執行Sorting事件
72  }
73  protected void btnSortByPostCodeAndAddress_Click(object sender, EventArgs e)
74  {
75    GridView1.Sort("MultiColumnSort", SortDirection.Ascending);
76  }
77}
78
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved