private void dgProducts_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Pager)
{
// 獲取DataGrid分頁區對象並為其指定PreRender事件的處理函數
pagerItem = e.Item;
pagerItem.PreRender += new System.EventHandler(this.pagerItem_PreRender);
}
}
private void pagerItem_PreRender(object sender, EventArgs e)
{
// 編寫事件處理代碼實現頁面統計信息以及跳頁功能
.......
}
在實現跳頁功能時我使用JavaScript將用戶在文本框中輸入的值保存在一個Html隱藏字段裡,然後在服務端獲取該隱藏字段的值,並將DataGrid指定到該頁,我曾經試過用URL傳參數的方式並指定window.location為新的URL字符串,可是使用window.location會導致Page_Load()執行兩次。從而得不到想要的結果。我也考慮過使用ViewState,可那個文本框和按鈕是動態添加進去的Html標簽,事先沒有在服務端定義,又如何操控它們呢!於是這個念頭也就一閃而過了!到最後也隻有採用"隱藏字段"這種不怎麼高級但確實能解決的方法。以下是點"go"按鈕時執行的JavaScript函數:
function go(ctrl,max)
{
// 驗証用戶輸入值是否符合要求
if(ctrl.value >= 1 && ctrl.value <= max.innerText)
{
// 將輸入值保存到隱藏字段裡
document.all.PageNum.value = ctrl.value;
}
else
{
alert('您輸入的頁碼必須是符合頁面要求的數字,最大值是:'+max.innerText);
ctrl.value="";
ctrl.focus();
return false;
}
}
全部代碼如下:
.Apsx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Sky_MsdnDataGrid
{
/// <summary>
/// SortDataGrid 的摘要描述。
/// </summary>
public class SortDataGrid : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgProducts;
private string connStr;
private string cmdText;
private DataGridItem pagerItem;
protected System.Web.UI.HtmlControls.HtmlInputHidden PageNum;
private int pagerNum = 1;
private DataTable productTable;
private void Page_Load(object sender, System.EventArgs e)
{
// 頁面加載時判斷隱藏字段中是否有值,如果有值代表用戶使用了跳頁功能,並將DataGrid的當前頁設為用戶指定頁
if (this.PageNum.Value != string.Empty)
{
this.dgProducts.CurrentPageIndex = Convert.ToInt32(this.PageNum.Value) - 1;
if (ViewState["SortExprName"] != null)
this.BindData("select * from Products order by " + ViewState["SortExprName"].ToString() + " asc");
else
this.BindData("select * from Products");
this.PageNum.Value = string.Empty;
}
else
{
this.BindData("select * from Products");
}
}
// 綁定數據
private void BindData(string sqlText)
{
this.connStr = "server=localhost;database=NorthWind;uid=sa";
this.cmdText = sqlText;
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
productTable = new DataTable("Products");
conn.ConnectionString = this.connStr;
cmd.CommandType = CommandType.Text;
cmd.CommandText = this.cmdText;
cmd.Connection = conn;
adapter.SelectCommand = cmd;
adapter.Fill(productTable);
this.dgProducts.DataSource = productTable;
this.dgProducts.DataBind();
}
#region Web Form 設計工具產生的程式碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 此為 ASP.NET Web Form 設計工具所需的呼叫。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 此為設計工具支援所必須的方法 - 請勿使用程式碼編輯器修改
/// 這個方法的內容。
/// </summary>
private void InitializeComponent()
{
this.dgProducts.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgProducts_ItemCreated);
this.dgProducts.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dgProducts_PageIndexChanged);
this.dgProducts.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgProducts_SortCommand);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
// 實現排序功能
private void dgProducts_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
this.dgProducts.CurrentPageIndex = 0;
ViewState["SortExprName"] = e.SortExpression;
this.BindData("select * from Products order by "+ e.SortExpression + " asc");
}
private void dgProducts_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
this.dgProducts.CurrentPageIndex = e.NewPageIndex;
if (ViewState["SortExprName"] != null)
this.BindData("select * from Products order by " + ViewState["SortExprName"].ToString() + " asc");
else
this.BindData("select * from Products");
}
private void dgProducts_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Pager)
{
// 獲取DataGrid分頁區對象並為其指定PreRender事件的處理函數
pagerItem = e.Item;
pagerItem.PreRender += new System.EventHandler(this.pagerItem_PreRender);
}
}
private void pagerItem_PreRender(object sender, EventArgs e)
{
if (this.pagerNum == 1)
{
this.pagerNum = this.pagerNum - 1;
return;
}
// currentPageNum-當前頁碼 recordCount-總記錄條數 pageCount-頁數
string currentPageNum = Convert.ToString(this.dgProducts.CurrentPageIndex + 1);
string recordCount = this.productTable.Rows.Count.ToString();
string pageCount = this.dgProducts.PageCount.ToString();
// 創建單元格包含頁面統計信息
TableCell groupCell = new TableCell();
groupCell.Text = "<b><font face='標楷體' size=3><font color=OliveDrab>當前第</font><font color=red>" + currentPageNum + "</font><font color=OliveDrab>頁 每頁<font color=red>" + this.dgProducts.PageSize.ToString() + "</font>條 (" +
"共</font><font color=red>" + recordCount + "</font><font color=OliveDrab>條,共</font><font color=red><label id='maxPage'>" + pageCount + "</label></font><font color=OliveDrab>頁)</font></font></b>";
// 創建單元格包含跳頁功能
TableCell operCell = new TableCell();
operCell.Text = "<input type='text' id='textbox' name='T1' size='4' style='border-style: solid; border-width: 1px; padding-left: 4px; padding-right: 4px; padding-top: 1px; padding-bottom: 1px'> " +
"<input type='submit' value='go' name='B1' onclick='return go(textbox,maxPage)' style='border-style: solid; border-width: 1px; padding-left: 4px; padding-right: 4px; padding-top: 1px; padding-bottom: 1px'>";
// pagerItem.Cells[0]代表DataGrid默認分頁,將其所跨列設為1
pagerItem.Cells[0].ColumnSpan = 1;
groupCell.HorizontalAlign = HorizontalAlign.Left;
groupCell.ColumnSpan = this.dgProducts.Columns.Count - 2;
operCell.HorizontalAlign = HorizontalAlign.Right;
pagerItem.Cells.AddAt(0,groupCell);
pagerItem.Cells.AddAt(2,operCell);
}
}
}
.Aspx
<%@ Page language="c#" Codebehind="SortDataGrid.aspx.cs" AutoEventWireup="false" Inherits="Sky_MsdnDataGrid.SortDataGrid" %>
<!DOCTYPE HTML PUBLIC "-//W
<HTML>
<HEAD>
<title>SortDataGrid</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<script language="javascript">
function go(ctrl,max)
{
// 驗証用戶輸入值是否符合要求
if(ctrl.value >= 1 && ctrl.value <= max.innerText)
{
// 將輸入值保存到隱藏字段裡
document.all.PageNum.value = ctrl.value;
}
else
{
alert('您輸入的頁碼必須是符合頁面要求的數字,最大值是:'+max.innerText);
ctrl.value="";
ctrl.focus();
return false;
}
}
</script>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="dgProducts" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 16px" runat="server" Width="100%" AllowSorting="True" AutoGenerateColumns="False" AllowPaging="True">
<FooterStyle ForeColor="#
<SelectedItemStyle Font-Bold="True" ForeColor="#F
<AlternatingItemStyle Font-Size="X-Small" BackColor="#CCFFFF"></AlternatingItemStyle>
<ItemStyle Font-Size="X-Small" BackColor="White"></ItemStyle>
<HeaderStyle Font-Size="X-Small" Font-Bold="True" HorizontalAlign="Center" ForeColor="White" BackColor="#99CCCC"></HeaderStyle>
<Columns>
<asp:BoundColumn DataField="ProductID" HeaderText="產品編號">
<HeaderStyle Width="15%"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="SupplierID" HeaderText="供應商編號">
<HeaderStyle Width="15%"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="ProductName" SortExpression="ProductName" HeaderText="產品名稱">
<HeaderStyle HorizontalAlign="Left" Width="30%"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="UnitPrice" SortExpression="UnitPrice" HeaderText="產品單價">
<HeaderStyle Width="20%"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="UnitsInStock" SortExpression="UnitsInStock" HeaderText="供應單價">
<HeaderStyle Width="20%"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
</Columns>
<PagerStyle Font-Size="X-Small" HorizontalAlign="Center" ForeColor="#
</asp:DataGrid>
<INPUT style="Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 256px" id="PageNum" runat="server" type="hidden">
</form>
</body>
</HTML>
最終運行效果: