簡體   English   中英

動態地將行添加到DataView的索引

[英]Dynamically adding rows to an index of a DataView

在將數據行插入到數據視圖中時,我遇到了一個有趣的問題。 我從數據庫接收到一組數據。 此信息被分組。 此數據集分為三個級別。 例如:

Category SaleValue
    SubCategory1 SaleValue
        SubCategory2 SaleValue
        SubCategory2 SaleValue
    SubCategory1 SaleValue
    SubCategory1 SaleValue
Category SaleValue
    ...

我已經為分組分配了整數值。 Category = 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;
}

好像我在想什么。 也許是因為我將循環的上限設置為原始數據。 插入是否弄亂了索引? 因為當我檢查比插入位置更高的索引時,插入的數據似乎重復出現或未在正確的索引處插入。

使用ObservableCollection和CollectionViewSource可能會更容易。
使用ObservableCollection.Add(item),然后刷新CollectionViewSource,如果您正確地設置了排序和分組設置,它將自動對數據進行排序和分組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM