[英]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.