簡體   English   中英

向數據表2添加行

[英]adding rows to a datatable #2

我有一個數據表,有些列是字符串,有些是十進制。 當我添加一行時,它會自動轉換信息還是我必須自己轉換它們? 我需要在表中添加很多數據,目前正在使用以下數據:

DataRow row = dataTable.NewRow();
row["item1"] = Info[0];
row["Item2"] = Info[1];
row["item3"] = Info[2];
row["Item4"] = Convert.ToDecimal(Info[3]);

Alex Mendez請查看以下鏈接: http : //msdn.microsoft.com/zh-cn/library/system.data.datatable.newrow.aspx ,我認為您缺少指示的代碼行(請參見下文) ):

foreach(Info info in infoList)
{
   DataRow row = dataTable.NewRow(); 
   row["item1"] = info.Item1; //where Item1 could be a string 
   row["Item2"] = info.Item2; //where Item2 could be an int
   row["item3"] = info.Item3; //Where Item3 could be a DateTime
   row["Item4"] = info.Item4; //Where Item4 could be a Decimal
   dataTable.Rows.Add(row); //<-- You need to add this line to actually save the value to the Data Table
}

row [“ ...”]是一個對象,可以采用任何類型。 如果您的Info [n]是字符串,則可以根據需要將其轉換為正確的類型。 我不知道Info是否是一個集合,但如果是,為什么不這樣做呢?

List<Info> infoList = new List<Info>();
infoList.Add(...); //Add item here.

foreach(Info info in infoList)
{
   DataRow row = dataTable.NewRow(); 
   row["item1"] = info.Item1; //where Item1 could be a string 
   row["Item2"] = info.Item2; //where Item2 could be an int
   row["item3"] = info.Item3; //Where Item3 could be a DateTime
   row["Item4"] = info.Item4; //Where Item4 could be a Decimal
}

檢查文檔: Datatable Addrow

如果未鍵入您的數據表,是的,您必須將數據轉換為預期的類型,如果鍵入了數據表,它將轉換數據,例如:

int number = "0";

您還可以設置列類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM