“不能通过行”访问删除的行信息“尝试从我的datatable中删除未使用的行 [英] "Deleted row information cannot be accessed through the row" trying to remove unused rows from my datatable

查看:246
本文介绍了“不能通过行”访问删除的行信息“尝试从我的datatable中删除未使用的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在抓住数据,将其粘贴到一个 DataTable 中,并将其显示在与 DataGridView 表。我试图使它使得datatable中不包括在当前抓取的数据被删除。我正在做如下:

I'm grabbing data, sticking it into a DataTable, and displaying it in a DataGridView bound to that table. Im trying to make it so that data in the datatable that is not included in the current grab is deleted. I'm doing it as follows:

public void FillTable(DataTable table, IEnumerable<MyObject> readings)
{
    var currentReadingsNames = new List<string>();
    var lastParent = string.Empty;
    var index = 0;

    foreach (var reading in readings)
    {
        if (reading.ParentName != lastParent)
        {
            lastParent = reading.ParentName;
            index = 0;
        }
        LoadRow(table, reading, index++);
        currentReadingsNames.Add(MakeKey(reading));
    }

    //Iterate through the rows in our data table. If the row is not one we just loaded, get rid of it.
    foreach (DataRow row in table.Rows)
    {
        if (!currentReadingsNames.Contains(MakeKey(row["ParentID"].ToString(), row["ID"].ToString())))
        {
            row.Delete();
        }
    }
    table.EndLoadData();
}

MakeKey(阅读) MakeKey(properties)返回一个字符串,我可以用来识别我的对象两种不同的方式。假设这是有效的。

MakeKey(reading) and MakeKey(properties) returns a string I can use to identify my object two different ways. Assume that this works.

当我运行这个,我得到:

When I run this, I get:


删除的行信息无法通过该行访问。

Deleted row information cannot be accessed through the row.

我觉得我不应该尝试访问已删除的行,因为我在完成查看其值( parentID ID 列)后,只能删除该行。这是否与我理解不同?任何想法为什么会这样发生?如果这个代码应该可以工作,也许这个错误在别的地方,但是我没有改变任何其他的东西,所以我会很惊讶(我试图添加这个删除行为)。

I feel like I shouldn't be attempted to access a deleted row, because I only delete the row after I'm done looking at its values (the parentID and ID column). Does this behave differently than I am understanding? Any ideas why this is happening? If this code should work, maybe the error is somewhere else, but I haven't changed anything else so I would be surprised (I'm trying to add this deleting behavior).

推荐答案

只需为已删除的行添加一个过滤器:

Just add a filter for deleted rows as:

foreach (DataRow row in table.Rows)
{
    if(row.RowState != DataRowState.Deleted) 
    {     
       if (!currentReadingsNames.Contains(MakeKey(row["ParentID"].ToString(), row["ID"].ToString())))
            {
                row.Delete();
            }
        }
    }

这篇关于“不能通过行”访问删除的行信息“尝试从我的datatable中删除未使用的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆