2014年3月3日 星期一

DataTable刪除欄位Column, 新增查詢刪除DataRow

How remove columns from ADO.NET DataTable?

DataTable remove column
dt.Columns.Remove(string name)
dt.Columns.Remove("id")
//or
dt.Columns.Remove(int index)
dt.Columns.Remove(0)

Create New DataTable
DataTable dt = new DataTable();

Create New Column
DataColumn column;
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "ID";
dt.Columns.Add(column);

Create new DataRow objects and add to DataTable.
DataRow row;
for (int i = 1; i <=10; i++)
{
   row = dt.NewRow();
   row["ID"]= i.ToString();
   dt.Rows.Add(row);
}

Select Row
row = dt.Select("ID='1'")[0];

Delete Row
row = dt.Select("ID='2'")[0];
row.Delete();

AcceptChanges
dt.AcceptChanges();

沒有留言:

張貼留言