分类: C#/.net
2013-01-21 09:16:48
删除DataRow:
有两种方法可以删除DataRow,Delete方法和Remove方法和RemoveAt方法。其区别是Delete方法实际上不是从DataTable中删除掉一行,而是将其标志为删除,仅仅是做个记号,而Remove方法则是真正的从DataRow中删除一行,RemoveAt方法是根本行的索引来删除。列:
DataRow dr=ds.Tables["table"].Rows.Find("a");
ds.Tables["table"].Remove(dr);
或
ds.Tables["table"].Remove(index);
//dr 为"a"所在的行,查出后将其删除,index为 "a"所在的索引号。关于DataSet中的其用法,参照MSDN
DataRow dr=ds.Tables["Customers"].Rows.Find("aaa");
if(dr.IsNull("ContactName");
.. else
dr["ContactName"]=DBNull.Value
//这里判断ContactName列是否为空,如果不是则为其赋空值,呵,很无厘头的做法,这里只为演示为列赋空值的做法。
using System.Data;
using System;
using System.Windows.Forms;
class DataT{
static DataTable dt;// = new DataTable();
static DataSet ds;
static void method1(){
dt = new DataTable("Name");
ds = new DataSet();
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Sex", typeof(string)));
dt.Columns.Add(new DataColumn("Addr", typeof(string)));
}
static void add(int id,string name,string sex,string addr){
DataRow dr = dt.NewRow();
dr["id"] = id;
dr["Name"] = name;
dr["Sex"] = sex;
dr["Addr"] = addr;
dt.Rows.Add(dr);
}
static void Main(){
DataT DT = new DataT();
method1();
add(100,"Join","Male","北京");
add(101,"Lily","feMale","北京");
add(102,"JIM","Male","北京");
ds.Tables.Add(dt);
foreach(DataRow dr in dt.Rows){
//MessageBox.Show(dr["ID"].ToString() + " " + dr["Name"].ToString() + " " + dr["Sex"].ToString() + " " +
// dr["Addr"].ToString(),"Message");
Console.WriteLine(dr["ID"].ToString() + " " + dr["Name"].ToString() + " " + dr["Sex"].ToString() + " " +