我在將數據行插入到數據視圖中時遇到了一個有趣的問題。我從數據庫收到一組數據。這些信息被分組。這個數據集有三個級別。例如:動態添加行到DataView的索引
Category SaleValue
SubCategory1 SaleValue
SubCategory2 SaleValue
SubCategory2 SaleValue
SubCategory1 SaleValue
SubCategory1 SaleValue
Category SaleValue
...
我已經爲分組分配了整數值。類別= 0,SubCategory1 = 1,SubCategory2 = 2。這將返回一個很好的DataView與所有正確的信息。
我的問題在於如何在特定索引處插入新數據。報告還有一個級別的數據。有一個最終級別的數據可以檢索。這包括每個級別的產品。例如(構建上述示例)。
Category SaleValue
SubCategory1 SaleValue
SubCategory2 SaleValue
Product SaleValue
Product SaleValue
SubCategory2 SaleValue
Product SaleValue
SubCategory1 SaleValue
SubCategory1 SaleValue
Category SaleValue
...
我需要將這些數據加入到相應的部分。不過,我覺得在我使用當前代碼插入時,插入操作會拋出DataView索引。這是我到目前爲止。請原諒我,如果我完全失去了一些東西。我是DataViews的新手。
private DataView AddProducts(DataView data)
{
int position = 0;
for (int i = position; i < data.Count; i++)
{
DataRowView currentRow = data[i];
if (current.Row.Field<int>("group") == 2)
{
var productData = //DB call for data
foreach (DataRowView row in productData)
{
position = i+1; //Dont want to insert at the row, but after.
DataRow newRow = data.Table.NewRow();
newRow[0] = row["ProductName"];
newRow[1] = row["Sale"];
data.Table.Rows.InsertAt(newRow, position);
// i is now position. This will allow another insert to insert on the
// next row, or for the loop to start at the row after this inserted
// row.
i = position;
}
}
}
return data;
}
這看起來像我缺少的東西。也許是因爲我將循環的上限設置爲原始數據。插入是否搞亂了索引?因爲當我檢查比我插入的索引更高的索引時,插入的數據似乎被重複或不被插入到正確的索引處。
我還沒有試過這種方法。然而,我確實遍歷了這個列表。我有一個位置計數器,可以跟蹤我在列表中的位置。然後,當我確定要插入的適當級別時,我在另一個循環中添加了新行。我增加了我的位置新增記錄的數量。一旦我跳出插入循環,我開始在插入循環設置位置持有者的位置搜索正確的行的外部循環。這會正確添加行。謝謝您的幫助! – Tom 2012-05-07 13:51:24