要先设置GridView的AllowSortring=true,这样当点击列标题的时候才能激发GridView的Sorting事件进行排序
1
using System;
2
using System.Data;
3
using System.Configuration;
4
using System.Collections;
5
using System.Web;
6
using System.Web.Security;
7
using System.Web.UI;
8
using System.Web.UI.WebControls;
9
using System.Web.UI.WebControls.WebParts;
10
using System.Web.UI.HtmlControls;
11
using System.Collections.Generic;
12
13
public 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78
