代码之家  ›  专栏  ›  技术社区  ›  Michael Kniskern

将新列和数据添加到已包含数据-c的datatable中#

  •  60
  • Michael Kniskern  · 技术社区  · 16 年前

    如何添加新的 DataColumn DataTable

    伪码

    //call SQL helper class to get initial data 
    DataTable dt = sql.ExecuteDataTable("sp_MyProc");
    
    dt.Columns.Add("NewColumn", type(System.Int32));
    
    foreach(DataRow row in dr.Rows)
    {
        //need to set value to NewColumn column
    }
    
    5 回复  |  直到 6 年前
        1
  •  136
  •   JohnB    10 年前

    继续你的代码-你在正确的轨道上:

    //call SQL helper class to get initial data 
    DataTable dt = sql.ExecuteDataTable("sp_MyProc");
    
    dt.Columns.Add("NewColumn", typeof(System.Int32));
    
    foreach(DataRow row in dt.Rows)
    {
        //need to set value to NewColumn column
        row["NewColumn"] = 0;   // or set it to some other value
    }
    
    // possibly save your Dataset here, after setting all the new values
    
        2
  •  13
  •   Musakkhir Sayyed    10 年前

    不是吗 foreach 而不是为了!?

    //call SQL helper class to get initial data  
    DataTable dt = sql.ExecuteDataTable("sp_MyProc"); 
    
    dt.Columns.Add("MyRow", **typeof**(System.Int32)); 
    
    foreach(DataRow dr in dt.Rows) 
    { 
        //need to set value to MyRow column 
        dr["MyRow"] = 0;   // or set it to some other value 
    } 
    
        3
  •  7
  •   Nishantha    11 年前

    只有您想设置默认值参数。这将调用第三个重载方法。

    dt.Columns.Add("MyRow", type(System.Int32),0);
    
        4
  •  7
  •   Akxaya    11 年前

    这里有一个减少For/ForEach循环的替代解决方案,这将减少循环时间并快速更新:)

     dt.Columns.Add("MyRow", typeof(System.Int32));
     dt.Columns["MyRow"].Expression = "'0'";
    
        5
  •  2
  •   Himanshu Shukla    11 年前

    试试这个

    > dt.columns.Add("ColumnName", typeof(Give the type you want));
    > dt.Rows[give the row no like  or  or any no]["Column name in which you want to add data"] = Value;