在GridView控制項中以DropDownList分頁

摘要:在GridView控制項中以DropDownList分頁

在.NET中的GridView控制項預設是以Link方式進行分頁,但其實可以按照自己的喜好方式進行方頁,要實現這個目標,有幾個地方必須先瞭解。

1.GridViewRow類別:GridView中呈現資料的資料列、標頭、頁尾、分頁欄,都是屬於這個類別。

2.GridView.BottomPagerRow屬性:這個屬性可以取得GridView的底端頁面巡覽列。

3.GridView_DataBound事件:GridView連繫資料完成後引發。

4.要會用FindControl方法

------實做------

首先GridView必須先啟動分頁(AllowPaging="True"),然後在PagerTemplate新增一個DropDownList控制項,用來控制分頁。

程式碼(C#):

01 protected void GridView1_DataBound(object sender, EventArgs e)
02 {
03
04     GridViewRow pagerRow = GridView1.BottomPagerRow; //取得GridView的底端頁面巡覽列
05
06    //取得巡覽列裡的DropDownList控制項(用FindControl方法)
07
08    DropDownList pageList = (DropDownList)pagerRow.FindControl("DropDownList1");
09
10    if (pageList != null) //判斷巡覽列有沒有出現(資料只有一頁就不會出現了)
11
12    {
13
14      //按分頁筆數新增項目(即頁碼)到DropDownList
15
16     for (int i = 0; i < GridView1.PageCount; i++)
17
18    {
19
20      //必須先將項目(即頁碼)新增到ListItem
21
22      int pageNumber = i + 1;
23
24      ListItem item = new ListItem(pageNumber.ToString());
25
26     //GridView目前停留的頁數,DropDownList選擇那個數
27
28      if (i == GridView1.PageIndex)
29
30 {
31
32 item.Selected = true;
33
34 }

35
36 //將ListItem增加到DropDownList
37
38 pageList.Items.Add(item);
39
40 }

41
42 }

43 }

44
45 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
46 {
47
48 GridViewRow pagerRow = GridView1.BottomPagerRow;
49
50 DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("DropDownList1");
51
52
53 GridView1.PageIndex = pageList.SelectedIndex ; //GridView呈現的index等於DropDownList選擇的index
54
55
56 }