为了账号安全,请及时绑定邮箱和手机立即绑定

如何执行单个DataRow对象的AcceptChanges And RejectChanges方法?

如何执行单个DataRow对象的AcceptChanges And RejectChanges方法?

小怪兽爱吃肉 2018-12-06 17:20:33
using System;using System.Data;using System.Data.SqlClient;public class Test{static void Main(){//Create a Table for two columns.DataTable tbl = CreateTable();//Added ten rowsAddData(tbl);DisplayTableInfo(tbl, "AcceptChanges之前的行状态");tbl.AcceptChanges();DisplayTableInfo(tbl, "AcceptChanges之后的行状态");ModifyData(tbl);DataRow row = tbl.Rows[3];Console.WriteLine(row.RowState);row.RejectChanges();row["item"] = "Deleted , Unchanged , Edited";row.AcceptChanges();//问题一:(1)//我想通过检测每个DataRow对象的行状态,如果是DataRowState.Deleted则进行AcceptChanges.//foreach(DataRow r in tbl.Rows)// if(r.RowState == DataRowState.Deleted)// r.AcceptChanges(); //当然以上方式将导致System.InvalidOperationException.//曾经使用过的方法(2) 这样可以完成以上的执行结果吗?//DataTable temp = tbl.GetChanges(DataRowState.Deleted);//当然可以使用tbl.AcceptChanges方法进行调用.但是我只想把那些DataRowState的枚举值为Deleted的//行进行AcceptChanges.DisplayTableInfo(tbl, "再次调用AcceptChanges之后的行状态");}public static DataTable CreateTable(){DataTable tbl = new DataTable("MyTable");DataColumn col;col = tbl.Columns.Add("id", Type.GetType("System.Int32"));col.AutoIncrement = true;col = tbl.Columns.Add("item", Type.GetType("System.String"));col.AllowDBNull = false;tbl.PrimaryKey = new DataColumn[] { tbl.Columns["id"] };return tbl;}public static void AddData(DataTable tbl){for (int i = 0; i < 10; i++){DataRow row = tbl.NewRow();row["item"] = "item " + i.ToString();tbl.Rows.Add(row);}}public static void ModifyData(DataTable tbl){DataRowCollection itemCollection = tbl.Rows;itemCollection[0].Delete();itemCollection[2].Delete();itemCollection[3].Delete();itemCollection[5].Delete();}public static void DisplayTableInfo(DataTable tbl, string msg){Console.WriteLine(tbl.TableName+" 中所有的数据:");foreach (DataRow row in tbl.Rows){foreach (DataColumn col in row.Table.Columns)Console.Write(row[col] + " , ");Console.WriteLine();}DisplayRowState(tbl, msg);}public static void DisplayRowState(DataTable tbl, string msg){Console.WriteLine(msg);foreach (DataRow row in tbl.Rows)Console.WriteLine(row.RowState);Console.WriteLine();}}//如果您对于DataTable,DataRow比较熟习,请把相关的代码附上.//不胜感激.//我将在线等待...
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 344 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信