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

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 rows
AddData(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比较熟习,请把相关的代码附上.
//不胜感激.
//我将在线等待...

小怪兽爱吃肉
浏览 345回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP