DataTable.Delete()在Accept Changes之前删除行

时间:2017-10-12 16:05:07

标签: vb.net datatable

我遇到了一个问题,我在循环中标记了几行要删除,但当它到达循环中的某个点时,实际上开始删除这些行。

正如您所看到的,我基本上正在检查是否需要删除该行,如果是,请将其添加到新表并删除它。

问题是这适用于前60行,然后突然显示行实际上被删除,并最终抛出一行,该索引不存在错误(在65)。

原始表格是包含名字,姓氏,电子邮件和公司的联系人列表,共有70条记录。

我试图将列表缩减一半,但问题开始发生在第23行左右。

            dtSelectCompany = dt_data.Clone
            Dim s_company As String
            Dim b_add As Boolean
            Dim dtCompanies As Data.DataTable

            For i = 0 To dt_data.Rows.Count - 1

                b_add = False

                s_company = dt_data.Rows(i).Item(columnsDictionary("company")).ToString

                If s_company = "" Then : b_add = True
                Else
                    dtCompanies = crm_functions.getCompaniesByName(s_company.Replace(" ", "%"))
                    If dtCompanies.Rows.Count > 1 Then : b_add = True
                    ElseIf dtCompanies.Rows.Count = 1 Then
                        dt_data.Rows(i).Item(columnsDictionary("company")) = dtCompanies.Rows(0).Item("id")
                    Else : b_add = True
                    End If

                End If

                If b_add Then
                    Dim temp_row As Data.DataRow = dtSelectCompany.NewRow
                    temp_row.ItemArray = dt_data.Rows(i).ItemArray.Clone()
                    temp_row.Item("fullName") = temp_row.Item(columnsDictionary("firstname")) & " " & temp_row.Item(columnsDictionary("lastname"))
                    dtSelectCompany.Rows.Add(temp_row)
                    dt_data.Rows(i).Delete()
                End If

            Next

1 个答案:

答案 0 :(得分:0)

使用数据行代替计数器,例如:

dtSelectCompany = dt_data.Clone
Dim s_company As String
Dim b_add As Boolean
Dim dtCompanies As Data.DataTable
Dim MyDataRow as DataRow
For Each MyDataRow IN dt_data.Rows
            b_add = False

            s_company = MyDataRow("company").ToString

            If s_company = "" Then : b_add = True
            Else
                ' not sure what crm_functions is, so left this alone
                dtCompanies = crm_functions.getCompaniesByName(s_company.Replace(" ", "%"))
                If dtCompanies.Rows.Count > 1 Then : b_add = True
                ElseIf dtCompanies.Rows.Count = 1 Then
                    MyDataRow("company")) = dtCompanies.Rows(0).Item("id")
                Else : b_add = True
                End If

            End If

            If b_add Then
                Dim temp_row As Data.DataRow = dtSelectCompany.NewRow
                temp_row = MyDataRow
                temp_row.Item("fullName") = temp_row.Item(columnsDictionary("firstname")) & " " & temp_row.Item(columnsDictionary("lastname"))
                dtSelectCompany.Rows.Add(temp_row)
                MyDataRow.Delete()
            End If
Next 

写下我的头顶,所以......