如何将New Column with Value添加到现有DataTable?

the*_*van 66 .net c# asp.net datatable visual-studio-2008

我有一个DataTable有5列和10行.现在我想向DataTable添加一个新列,我想将DropDownList值分配给New Column.所以DropDownList值应该添加10次到New Column.这该怎么做?注意:不使用FOR LOOP.

例如:我的现有DataTable是这样的.

   ID             Value
  -----          -------
    1              100
    2              150
Run Code Online (Sandbox Code Playgroud)

现在我想在此DataTable中添加一个新列"CourseID".我有一个DropDownList.它的选择值是1.所以我现有的表应如下所示:

    ID              Value         CourseID
   -----            ------       ----------
    1                100             1
    2                150             1
Run Code Online (Sandbox Code Playgroud)

这该怎么做?

Kei*_*ton 121

没有For循环:

Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))     
newColumn.DefaultValue = "Your DropDownList value" 
table.Columns.Add(newColumn) 
Run Code Online (Sandbox Code Playgroud)

这是未经测试的.我使用了在线C#转换工具:

System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
Run Code Online (Sandbox Code Playgroud)

  • +1我把它拿回来.使用`DefaultValue`*设置列然后*将其添加到`Columns`集合中具有应用于所有现有行的所需效果.但是,将它添加到`Columns`然后设置`DefaultValue`不会产生相同的结果(在这种情况下,它只适用于新添加的行而不是现有的行). (11认同)

Tim*_*ter 13

添加列并更新其中的所有行DataTable,例如:

DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
    DataRow row = tbl.NewRow();
    row["ID"] = i;
    row["Name"] = i + ". row";
    tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
    row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;
Run Code Online (Sandbox Code Playgroud)

  • OP 不是说 **WITHOUT USING FOR LOOP**!? (2认同)