[英]How to add new rows to DataTable only under specific columns?
我有一個DataTable,dt2,我試圖在其中添加新行(在下面的代碼的else塊中)。 我不能簡單地在foreach循環中添加行(我在dt2.Rows.Add(newRow);
行中嘗試過dt2.Rows.Add(newRow);
因為這會dt2.Rows.Add(newRow);
循環計數器或其他東西,並導致以下錯誤: “集合已被修改;枚舉操作可能不執行。”
因此,我嘗試將新的行值存儲在List中,然后將List添加到循環外的表中。 從某種意義上說,它可以編譯並確實添加了一些東西。 不幸的是,它沒有采用正確的值或列位置,而是顯示了以下廢話: System.Collections.Generic.List`1 [System.Object]
另外,該信息應顯示在Target_Folder,Target_File和Target_Checksum下的第3、4和5索引列中,而不是在Baseline_Folder下。
如何在正確的列下存儲和顯示正確的值?
foreach (DataRow drow in dt2.Rows)
{
if (drow["BASELINE_FILE"].ToString() == filename)
{
// do stuff
}
else
{
newRow = dt2.NewRow(); // newRow is a DataRow I declared up above
newRow[3] = directory;
newRow[4] = filename;
newRow[5] = checksumList[j];
newRow[6] = "Missing";
//dt2.Rows.Add(newRow);
// can't add here because that increases the number of rows and screws up the foreach loop
// therefore need to find way to store these values and add outside of loop
newFiles.Add(newRow); // newFiles is a List
}
}
dt2.Rows.Add(newFiles); // this doesn't work properly, doesn't take correct values
這是我的頭上的事,但是遵循以下幾條原則應該可以起作用:
DataRow dr = dt2.NewRow();
foreach (ListItem item in newFiles.Items)
{
dr[3] = item[3].ToString();
dr[4] = item[4].ToString();
etc.
}
如果您需要更多指導,請告訴我,我會加倍努力。
我認為這是您真正想要做的:
DataRow[] drx = dt2.Select(string.Format("BASELINE_FILE = '{0}'" , filename));
if (drx.Length == 1)
{
// do stuff with drx[0]
}
else
{
newRow = dt2.NewRow(); // newRow is a DataRow I declared up above
newRow[3] = directory;
newRow[4] = filename;
newRow[5] = checksumList[j];
newRow[6] = "Missing";
dt2.Rows.Add(newRow);
}
這樣,您就不需要遍歷所有行。
如果您希望遍歷現有網格中的每一行,則應該為您完成。 這樣循環運行時就不會修改currentRows,因為它將是該列表的淺表副本。
var currentRows = from row in dataTable.Rows select row;
foreach (var row in currentRows)
{
if(doStuffCondition){ doStuff();}
else{
DataRow newRow = dataTable.NewRow();
newRow[1] = newValue; //repeat until values are loaded
employeesDataTable.Rows.Add(newRow);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.