大家都知道在一個datatable中刪除datarow有兩個方法,調用remove()和delete()方法。
其中remover()方法是直接刪除,delete()方法則是先做標記,再調用AcceptChanges()的時候纔會刪除。但是有時候會發現delete()在調用AcceptChanges()之前也會直接刪除,這是爲什麼呢。
如下一段代碼在調試過程中就會發現會有異常。
using System;
using System.Text;
using System.Collections;
using System.Data;
namespace Test
{
class TEST1
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
CreatDataSetSchema(ds);
InitData(ds);
int count = ds.Tables[0].Rows.Count;
for (int i =0 ; i < count ; i++ )
{
ds.Tables[0].Rows[i].Delete();
Console.WriteLine(ds.Tables[0].Rows.Count.ToString());
}
Console.WriteLine("end");
Console.ReadLine();
}
//初始化數據集結構
private static void CreatDataSetSchema(DataSet ds)
{
DataTable dt = new DataTable("Hosts");
DataColumn dc = new DataColumn("HId", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("IsLocal", typeof(Boolean));
dt.Columns.Add(dc);
ds.Tables.Add(dt);
}
//加入數據
private static void InitData(DataSet ds)
{
DataRow hostsRow = ds.Tables["Hosts"].NewRow();
hostsRow["HId"] = "192.168.1.1";
hostsRow["IsLocal"] = true;
ds.Tables["Hosts"].Rows.Add(hostsRow);
hostsRow = ds.Tables["Hosts"].NewRow();
hostsRow["HId"] = "192.168.1.2";
hostsRow["IsLocal"] = false;
ds.Tables["Hosts"].Rows.Add(hostsRow);
hostsRow = ds.Tables["Hosts"].NewRow();
hostsRow["HId"] = "192.168.1.3";
hostsRow["IsLocal"] = false;
ds.Tables["Hosts"].Rows.Add(hostsRow);
hostsRow = ds.Tables["Hosts"].NewRow();
hostsRow["HId"] = "192.168.1.4";
hostsRow["IsLocal"] = false;
ds.Tables["Hosts"].Rows.Add(hostsRow);
}
}
}
通過調試中查看ds對象的數據發現在調用delete()方法後數據被刪除了,而不是被置爲刪除標記。爲什麼會有這種情況呢,很多網上的文章和MSDN的幫助都說的是做標記而不是刪除?
我也被這種情況折騰了兩天,快要放棄的情況下想到我的另外一個delete()方法就是置爲刪除標記,兩者的區別就是一個是直接從數據庫填充的數據,而這個是自己手動添加的數據,於是想到了試試在插入完成數據庫調用AcceptChanges()方法。
上面的main方法代碼修改爲如下:
static void Main(string[] args)
{
DataSet ds = new DataSet();
CreatDataSetSchema(ds);
InitData(ds);
//調用delete方法前保存數據插入
ds.Tables[0].AcceptChanges();
int count = ds.Tables[0].Rows.Count;
for (int i =0 ; i < count ; i++ )
{
ds.Tables[0].Rows[i].Delete();
Console.WriteLine(ds.Tables[0].Rows.Count.ToString());
}
Console.WriteLine("end");
Console.ReadLine();
}
這個時候調試就正確了,能夠在ds對象上看到數據都被標記爲刪除了。