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>
	/// DataGridMulUse 的摘要说明。
	/// </summary>
	public class DataGridMulUse : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.TextBox RowCount;
		protected System.Web.UI.WebControls.LinkButton AddRow;
		protected System.Web.UI.WebControls.DataGrid dgEditInfo;
		protected System.Web.UI.WebControls.DataGrid dgSaveInfo;
		protected System.Web.UI.WebControls.ValidationSummary ValidationSummary1;
		protected System.Web.UI.WebControls.Button btnSave;
	
		private DataSet dataSet = new DataSet();
		private int lastEditedPage;
		private void Page_Load(object sender, System.EventArgs e)
		{
			if(!IsPostBack)
			{
				//进行数据绑定
				DataGridDataBind();
			}
		}
		
		public void ReverseBind()
		{
			//循环取得DataGrid控件中的项，并把每项的数据保存到DataSet中
			foreach(DataGridItem gridrow in dgEditInfo.Items)
			{
				//建立DataSet中testTable表的新行
				DataRow row = dataSet.Tables["testTable"].NewRow();
				//针对绑定数据源的数据项索引建立数据行的索引
				row = dataSet.Tables["testTable"].Rows[gridrow.DataSetIndex];
				//取得当前行文本框中的数据值,添加到DataSet中testTable表
				row["LastName"] = ((TextBox)(gridrow.FindControl("LastName"))).Text;
				row["FirstName"] = ((TextBox)(gridrow.FindControl("FirstName"))).Text;
				row["City"] = ((TextBox)(gridrow.FindControl("City"))).Text;
				row["ReportsTo"] = Convert.ToInt32(((TextBox)(gridrow.FindControl("Reports"))).Text);
			}
		}
		
		protected override void LoadViewState(object savedState)
		{
			base.LoadViewState(savedState);

			//取得编辑前的DataSet的视图状态
			if (ViewState["Data"]!= null) 
			{
				dataSet = (DataSet)ViewState["Data"];
			}

			if (ViewState["LastEditedPage"] != null)
			{
				//取得视图状态中保存的当前页的索引
				lastEditedPage = Convert.ToInt32(ViewState["LastEditedPage"]);
			}

		}

		protected override object SaveViewState()
		{
			//保存当前DataSet的视图状态
			ViewState["Data"] = dataSet;
			//保存当前页面索引的视图状态
			ViewState["LastEditedPage"] = lastEditedPage;
			return (base.SaveViewState());
		}
		//进行数据绑定
		private void DataGridDataBind()
		{
			//定义数据连接对象,其中数据库连接字符串是在Web.Config文件中定义的
			SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionSqlServer"].ToString());
			//创建数据适配器对象
			SqlDataAdapter da = new SqlDataAdapter("select top 3 LastName,FirstName,ReportsTo,City from Employees",conn);
			try
			{
				//填充数据集
				da.Fill(dataSet,"testTable");
				//进行数据绑定
				dgEditInfo.DataSource = dataSet.Tables["testTable"];
				dgEditInfo.DataBind();
			}
			catch(Exception error)
			{
				Response.Write(error.ToString());
			}		
		}
		public void BindGrid()
		{
			//进行数据绑定
			dgEditInfo.DataSource = dataSet.Tables["testTable"];
			dgEditInfo.DataBind();
			lastEditedPage = dgEditInfo.CurrentPageIndex;
		}
		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{    
			this.dgEditInfo.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgEditInfo_ItemCommand);
			this.dgEditInfo.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dgEditInfo_PageIndexChanged);
			this.AddRow.Click += new System.EventHandler(this.AddRow_Click);
			this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void AddRow_Click(object sender, System.EventArgs e)
		{
			//如果输入了添加的行数
			if (RowCount.Text.Trim() != "")
			{
				try
				{
					int addRowCount = Convert.ToInt32(RowCount.Text);
					for(int i = 0;i<addRowCount;i++)
					{
						//为当前绑定的数据表添加新行
						DataRow row = dataSet.Tables["testTable"].NewRow();
						row[0] = "";
						row[1] = "";
						row[2] = "0";
						row[3] = "";
						dataSet.Tables["testTable"].Rows.Add(row);	
					}
				}
				catch
				{
					Response.Write("请输入正确的要添加的行数");
				}
				
			}
			//重新进行数据绑定
			BindGrid();
		}

		private void btnSave_Click(object sender, System.EventArgs e)
		{
			//取得当前DataGrid中的数据
			ReverseBind();
			dgSaveInfo.DataSource = dataSet.Tables["testTable"];
			dgSaveInfo.DataBind();
		}

		private void dgEditInfo_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			if("Delete" == e.CommandName)
			{
				//移除当前绑定的数据表中的指定行
				dataSet.Tables["testTable"].Rows.Remove(dataSet.Tables["testTable"].Rows[e.Item.DataSetIndex]);
				//防止最后页删除唯一的一条记录时出现异常信息
				if ((dgEditInfo.PageCount - dgEditInfo.CurrentPageIndex) == 1 && dgEditInfo.Items.Count == 1)
				{
					if (dgEditInfo.PageCount > 1)
					{
						lastEditedPage = lastEditedPage - 1;
					}
					else
					{
						lastEditedPage = 0;
					}
				}
				dgEditInfo.CurrentPageIndex = lastEditedPage;
				BindGrid();
			}
		}

		private void dgEditInfo_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			//设置DataGrid当前页的索引
			dgEditInfo.CurrentPageIndex = e.NewPageIndex;
			BindGrid();
		}
	}
}
