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>
	/// PagerState 的摘要说明。
	/// </summary>
	public class PagerState : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.DataGrid dgPagerState;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			if(!IsPostBack)
			{
				//设置排序表达式
				ViewState["SortOrder"] = "LastName";
				//设置排序的升降序
				ViewState["OrderDire"] = "ASC";
				//数据绑定
				DataGridDataBind();
			}
		}

		private void DataGridDataBind()
		{
			//定义数据连接对象,其中数据库连接字符串是在Web.Config文件中定义的
			SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionSqlServer"].ToString());
			//创建数据适配器对象
			SqlDataAdapter da = new SqlDataAdapter("select LastName,FirstName,Title,TitleOfCourtesy,BirthDate,City from Employees",conn);
			//创建DataSet对象
			DataSet ds = new DataSet();
			try
			{
				//填充数据集
				da.Fill(ds,"testTable");
				//取得填充表格的默认视图
				DataView view = ds.Tables["testTable"].DefaultView;
				//设置排序关键字
				string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
				//设置排序表达式
				view.Sort =  sort;
				//数据邦定
				dgPagerState.DataSource = view;
				dgPagerState.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.dgPagerState.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dgPagerState_PageIndexChanged);
			this.dgPagerState.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgPagerState_SortCommand);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void dgPagerState_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			//设置DataGrid的当前显示页的索引值为选择的页面索引值
			dgPagerState.CurrentPageIndex = e.NewPageIndex;
			DataGridDataBind();
		}

		private void dgPagerState_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
		{
			//取得排序表达式
			string vortExp = e.SortExpression;
			//如果是当前排序表达式
			if(ViewState["SortOrder"].ToString() == vortExp)
			{
				//如果原来是降序则改为升序，反之亦然
				if((string)ViewState["OrderDire"] == "Desc")
					ViewState["OrderDire"] = "ASC";
				else
					ViewState["OrderDire"] = "Desc";
			}
			else
			{
				//重新设置排序关键字
				ViewState["SortOrder"] = e.SortExpression;
			}
			DataGridDataBind();
		}
	}
}
