溫馨提示×

C#中DataTable怎么使用

小億
155
2023-08-04 20:54:08
欄目: 編程語言

在C#中,DataTable是一個類,用于在內(nèi)存中存儲和操作數(shù)據(jù)。要使用DataTable,需要先創(chuàng)建一個DataTable對象,然后可以添加列、添加行、修改數(shù)據(jù)等操作。

以下是一些常用的DataTable操作:

  1. 創(chuàng)建DataTable對象:
DataTable dt = new DataTable("MyTable");
  1. 添加列:
dt.Columns.Add("Column1", typeof(int));
dt.Columns.Add("Column2", typeof(string));
  1. 添加行:
DataRow row = dt.NewRow();
row["Column1"] = 1;
row["Column2"] = "Value";
dt.Rows.Add(row);
  1. 修改數(shù)據(jù):
dt.Rows[0]["Column1"] = 2;
  1. 遍歷數(shù)據(jù):
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
Console.WriteLine(row[col]);
}
}
  1. 查詢數(shù)據(jù):
DataRow[] result = dt.Select("Column1 = 2");
foreach (DataRow row in result)
{
Console.WriteLine(row["Column2"]);
}
  1. 刪除行:
dt.Rows[0].Delete();
dt.AcceptChanges();  // 提交更改
  1. 清空數(shù)據(jù)表:
dt.Clear();

請注意,以上只是一些基本的操作,DataTable還有更多的功能,如排序、過濾、關(guān)聯(lián)等,可以根據(jù)具體的需求進(jìn)行進(jìn)一步學(xué)習(xí)和使用。

0