使用循环检查数据表在所选索引处是否有行

时间:2014-06-28 09:52:33

标签: vb.net

使用for循环检查数据表是否在所选索引处具有行

我想在这里查看数据表是否有该行的值为' i'来自循环

   Private Sub btnAct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAct.Click


    Gross = 0
    Dim i As Integer

    Dim dr As DataRow = Nothing
    Act1 = dt.Rows(0)("Account")
    Act2 = dt.Rows(0)("Account")

    'Next
    For i = 0 To 100 Step 1
        If ( i Want to check here if datatable has row at that value of 'i' which comes from loop) Then

else

 If (Act1 = Act2) Then

        Else

            Act1 = dt.Rows(i - 1)("Account")

            For k As Integer = 0 To (i - 1) Step 1

                Act2 = Convert.ToString(dt.Rows(k)("Account"))

                If (Act1 = Act2) Then

                    Gross += Convert.ToInt32(dt.Rows(k)("Total_Gross_Amount"))

                End If

            Next

            dr = dt.NewRow()

            dr("Account") = "Total"
            dr("Total_Gross_Amount") = Gross
            Gross = 0
            dt.Rows.InsertAt(dr, i)
            Act2 = Convert.ToString(dt.Rows(i + 1)("Account"))

        End If
        Act1 = Convert.ToString(dt.Rows(i + 1)("Account"))

        dt(i)("Sno") = i + 1
    Next


        End If




    'Next

End Sub

我有一个数据表而且我想检查它是否有来自for循环的选定值的行

1 个答案:

答案 0 :(得分:2)

简单 - LINQ救援:

For i = 0 To 100
  ' Functionally equivalent to
  ' dt.Rows.Cast(Of DataRow)().ElementAtOrDefault(i).
  Dim rowAtIndex = dt.AsEnumerable().ElementAtOrDefault(i)

  If rowAtIndex IsNot Nothing Then
    ' Do something with the row.
  End If
Next

或稍微不那么富有表现力但更优化的版本:

For i = 0 To 100
  Dim rowAtIndex As DataRow = Nothing

  If i < dt.Rows.Count Then
    rowAtIndex = dt.Rows(i)

    ' Do something with the row.
  Else
    ' Row at index does not exist.
  End If
Next

这里最大的问题是: i确实需要超越 dt.Rows.Count - 1(这是DataTable中最后一行的索引) ?如果没有,我宁愿将循环更改为

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