简体   繁体   English

在一行中用 NewRow 写一个 Add Row

[英]Write an Add Row with NewRow in one line

I would like to add a new row in an existing table.我想在现有表中添加一个新行。 I want to create a new row with the NewRow method and put the values on the same line.我想用 NewRow 方法创建一个新行并将值放在同一行上。

DataTable dtTable1 = new DataTable();
dtTable1.Rows.Add(new DataColumn(NCdeTCMParametrs.NombreCol1), typeof(string));
dtTable1.Rows.Add(new DataColumn(NCdeTCMParametrs.NombreCol2()), typeof(string)); 
        
        
dtTable1.Rows.Add(dtTable1.NewRow() { new object[] { datCol1, string.Join(",", listCol2) } });

I can't find the correct syntax for it to be accepted.我找不到正确的语法来接受它。 What is the mistake?什么是错误?

You just need to use DataRowCollection.Add that takes an Object[] :您只需要使用带有Object[] DataRowCollection.Add

dtTable1.Rows.Add(new object[] { datCol1, string.Join(",", listCol2) });

DataTable.NewRow is used if you want to initialize each field separately, so you don't need it if you want to pass the whole array at once.如果要单独初始化每个字段,则使用DataTable.NewRow ,因此如果要一次传递整个数组,则不需要它。 You could also use NewRow and initialize all fields at once with ItemArray , but you need multiple lines:您还可以使用NewRow并使用ItemArray一次初始化所有字段,但您需要多行:

DataRow row = dtTable1.NewRow();
row.ItemArray = new object[] { datCol1, string.Join(",", listCol2) };
dtTable1.Rows.Add(row);

A third option is to add an empty row and afterwards modify the already added row:第三种选择是添加一个空行,然后修改已添加的行:

DataRow addedRow = dtTable1.Rows.Add();
addedRow.ItemArray = new object[] { datCol1, string.Join(",", listCol2) };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM