2012-02-23 79 views
0

我在将数据行插入到数据视图中时遇到了一个有趣的问题。我从数据库收到一组数据。这些信息被分组。这个数据集有三个级别。例如:动态添加行到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; 
} 

这看起来像我缺少的东西。也许是因为我将循环的上限设置为原始数据。插入是否搞乱了索引?因为当我检查比我插入的索引更高的索引时,插入的数据似乎被重复或不被插入到正确的索引处。

回答

1

使用ObservableCollection和CollectionViewSource可能更容易。
使用ObservableCollection.Add(item),然后刷新CollectionViewSource会自动排序和分组数据,如果你有正确的排序和分组设置。

+0

我还没有试过这种方法。然而,我确实遍历了这个列表。我有一个位置计数器,可以跟踪我在列表中的位置。然后,当我确定要插入的适当级别时,我在另一个循环中添加了新行。我增加了我的位置新增记录的数量。一旦我跳出插入循环,我开始在插入循环设置位置持有者的位置搜索正确的行的外部循环。这会正确添加行。谢谢您的帮助! – Tom 2012-05-07 13:51:24