85

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
}
4

5 に答える 5

142

あなたのコードを続けてください-あなたは正しい軌道に乗っています:

//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
于 2010-02-22T18:25:36.977 に答える
13

foreachforの代わりにすべきではありません!?

//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 
} 
于 2012-01-06T20:54:40.587 に答える
8

For / ForEachループを減らすための代替ソリューションを次に示します。これにより、ループ時間が短縮され、すばやく更新されます:)

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";
于 2015-03-02T22:16:48.133 に答える
7

デフォルト値パラメータを設定したいのはあなただけです。この呼び出しの3番目のオーバーロードメソッド。

dt.Columns.Add("MyRow", type(System.Int32),0);
于 2015-02-18T10:51:46.857 に答える
2

これを試して

> 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;
于 2015-07-14T18:03:15.857 に答える