今天主要是讲如何利用ADO.NET的DataTable对象的事件处理函数,来操作数据。进行行的添加,删除,以及内容的修改。 protected void Page_Load( object sender, EventArgs e) ... { DataTable TestTable = CreatTabele(); //设置事件处理函数 TestTable.ColumnChanged += new DataColumnChangeEventHandler(TestTable_ColumnChanged); TestTable.ColumnChanging += new DataColumnChangeEventHandler(TestTable_ColumnChanging); //TestTable.RowChanged += new DataRowChangeEventHandler(TestTable_RowChanged); //TestTable.RowChanging += new DataRowChangeEventHandler(TestTable_RowChanging); //TestTable.RowDeleted +=new DataRowChangeEventHandler(TestTable_RowDeleted); //TestTable.RowDeleting +=new DataRowChangeEventHandler(TestTable_RowDeleting); //修改数据行 TestTable.Rows[0]["Name"] = "Test"; GridView gvTable = new GridView(); gvTable.DataSource = CreatTabele(); gvTable.DataBind(); PlaceHolder1.Controls.Add(gvTable); } private void TestTable_ColumnChanging( object sender, DataColumnChangeEventArgs e) ... { this.Label4.Text = "TestTable_ColumnChanging"; this.Label5.Text = e.Row["Name"].ToString(); this.Label6.Text = e.Row.RowState.ToString(); } private void TestTable_ColumnChanged( object sender, DataColumnChangeEventArgs e) ... { this.Label1.Text = "TestTable_ColumnChanged"; this.Label2.Text = e.Row["Name"].ToString(); this.Label3.Text = e.Row.RowState.ToString(); } // 建立数据表 private DataTable CreatTabele() ... { //long StartTime = DateTime.Now.Ticks; //新建表 DataTable Table = new DataTable("User"); Table.Columns.Add("ID", typeof(System.Int32)); Table.Columns.Add("Name", typeof(System.String)); Table.Columns.Add("Pwd", typeof(System.String)); Table.PrimaryKey = new DataColumn[] ...{ Table.Columns["ID"] }; Table.Columns["ID"].AutoIncrement = true; Table.Columns["ID"].AutoIncrementSeed = 1; Table.Columns["ID"].ReadOnly = true; //填充数据行 DataRow TmpRow; for (int i = 0; i < 100; i++) ...{ TmpRow = Table.NewRow(); //偶数行 if (Math.IEEERemainder(i, 2) == 0) ...{ TmpRow["Name"] = "weiwei"; TmpRow["Pwd"] = 123456; } //奇数行 else ...{ TmpRow["Name"] = "tommy"; TmpRow["Pwd"] = 159357; } Table.Rows.Add(TmpRow); } Table.AcceptChanges(); //long EndTime = DateTime.Now.Ticks; //显示创建一个表需要的时间 //Response.Write("用时:" + (EndTime - StartTime)); //返回新建好的表 return Table; }