向数据表中添加行 #2

4

我有一个数据表,其中一些列是字符串,一些是小数。当我添加一行时,它会自动转换信息还是我需要自己转换?我有很多数据需要添加到表中,目前我正在使用以下方法:

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

1

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
}

1

Alex Mendez请查看此链接: http://msdn.microsoft.com/en-us/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
}

0
如果您的DataTable没有类型,那么您必须将数据转换为预期的类型;如果是有类型的DataTable,则会自动转换数据,例如:
int number = "0";

您还可以设置列类型。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接