如何将带值的新列添加到现有数据表中

本文关键字:数据表 添加 新列 | 更新日期: 2023-09-27 17:59:42

我有一个5列10行的DataTable。现在,我想向DataTable添加一个NewColumn,并将DropDownList值分配给NewColumn。因此,DropDownList值应该添加到NewColumn中10次。如何做到这一点?注意:不使用FOR LOOP。

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

   ID             Value
  -----          -------
    1              100
    2              150

现在,我想在这个数据表中添加一个新列"CourseID"。我有一个下拉列表。其选定值为1。所以我现有的表格应该如下:

    ID              Value         CourseID
   -----            ------       ----------
    1                100             1
    2                150             1

如何做到这一点?

如何将带值的新列添加到现有数据表中

无For循环:

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

C#:

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

添加列并更新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;
//Data Table
 protected DataTable tblDynamic
        {
            get
            {
                return (DataTable)ViewState["tblDynamic"];
            }
            set
            {
                ViewState["tblDynamic"] = value;
            }
        }
//DynamicReport_GetUserType() function for getting data from DB

System.Data.DataSet ds = manage.DynamicReport_GetUserType();
                tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
                tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]

                for (int i = 0; i < tblDynamic.Rows.Count; i++)
                {
                    if (tblDynamic.Rows[i]["Type"].ToString()=="A")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Apple";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "B")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Ball";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "C")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Cat";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "D")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Dog;
                    }
                }