datagridcustompage.aspx.cs

来自「asp.net专家200问(含源代码解决法案」· CS 代码 · 共 89 行

CS
89
字号
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
namespace CommonFunction
{
	/// <summary>
	/// DataGridCustomPage 的摘要说明。
	/// </summary>
	public class DataGridCustomPage : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.DataGrid dgCustomPage;
		//定义全局变量用来保存每页的起始项索引
		int startIndex=0;
		private void Page_Load(object sender, System.EventArgs e)
		{
			//页面初试化时进行数据绑定
			if(!IsPostBack)
				DataGridDataBind();
		}
		private void DataGridDataBind()
		{
			//定义数据连接对象,其中数据库连接字符串是在Web.Config文件中定义的
			SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionSqlServer"].ToString());
			//创建数据适配器对象
			SqlDataAdapter da = new SqlDataAdapter("select LastName,FirstName,BirthDate,City from Employees",conn);
			//创建DataSet对象
			DataSet ds = new DataSet();
			try
			{
				//从指定的索引开始取PageSize条记录
				da.Fill(ds,startIndex,dgCustomPage.PageSize,"CurDataTable");
				//填充数据集
				da.Fill(ds,"AllDataTable");
				//设置DataGrid控件实际要显示的项数
				dgCustomPage.VirtualItemCount = ds.Tables["AllDataTable"].Rows.Count;
				//进行数据绑定
				dgCustomPage.DataSource = ds.Tables["CurDataTable"];
				dgCustomPage.DataBind();
			}
			catch(Exception error)
			{
				Response.Write(error.ToString());
			}	
		}


		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{    
			this.dgCustomPage.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dgCustomPage_PageIndexChanged);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void dgCustomPage_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			//设置DataGrid当前页的索引值为用户选择的页的索引
			dgCustomPage.CurrentPageIndex = e.NewPageIndex;
			//取得当前页为止总共有多少条记录,以便在下一页就从该记录开始读取
			startIndex = dgCustomPage.PageSize * dgCustomPage.CurrentPageIndex;
			//重新绑定数据
			DataGridDataBind();
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?