[英]DataTable.ImportRow is not adding rows
我正在嘗試創建一個DataTable,然后添加幾行。 這是我的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace thisNamespace
{
class Program
{
static void Main(string[] args)
{
DataTable dt=new DataTable();
dt.Columns.Add("XYZID");
DataRow dr=dt.NewRow();
dr["XYZID"]=123;
dt.ImportRow(dr);
dr["XYZID"] = 604303;
dt.ImportRow(dr);
}
}
}
當我逐步完成程序時, dr
已成功初始化並填充了值,但是在ImportRow(dr)
, dt
的行數仍為0.我覺得我必須遺漏一些明顯的東西。 這里出了什么問題?
試試這段代碼:
dt.Rows.Add(dr)
如果該行是分離的(就像它在第一次創建時那樣),則ImportRows會以靜默方式失敗(沒有異常) - 能夠導入您必須將行添加到表中的行。 之后,您可以將其導入其他表。
它可以幫助你
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
首先需要添加行:
dt.Rows.Add(dr);
然后你必須調用以下方法來提交它:
dt.AcceptChanges();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.