【问题标题】:Dynamically adding rows to an index of a DataView将行动态添加到 DataView 的索引
【发布时间】:2012-02-23 17:29:17
【问题描述】:

我在将数据行插入数据视图时遇到了一个有趣的问题。我从数据库中收到一组数据。该信息被分组。该数据集共有三个级别。例如:

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

这似乎我错过了一些东西。也许是因为我将循环的上限设置为原始 data.Count 数?插入是否弄乱了索引?因为当我检查比插入位置更高的索引时,插入的数据似乎重复或未插入到正确的索引处。

【问题讨论】:

    标签: c# datatable dataview


    【解决方案1】:

    使用 ObservableCollection 和 CollectionViewSource 可能更容易。
    使用 ObservableCollection.Add(item) 然后刷新 CollectionViewSource 如果您正确设置了排序和分组,它将自动对数据进行排序和分组。

    【讨论】:

    • 这个方法我没试过。但是,我确实遍历了列表。我有一个位置计数器,可以跟踪我在列表中的位置。然后,当我确定要插入的适当级别时,我在另一个循环中添加了新行。我增加了我添加的新记录的数量。一旦我跳出插入循环,我就会启动外部循环,在插入循环将位置保持器设置到的位置处搜索正确的行。这会正确添加行。感谢您的帮助!
    猜你喜欢
    • 2017-05-25
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2015-11-21
    相关资源
    最近更新 更多