【发布时间】: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 数?插入是否弄乱了索引?因为当我检查比插入位置更高的索引时,插入的数据似乎重复或未插入到正确的索引处。
【问题讨论】: