如何循环数据表中的行?

时间:2013-02-12 01:52:30

标签: asp.net vb.net

我在查看循环以查看更多信息时遇到了一些问题。引用的数据集函数可以获得所有必需的行,因此我确定问题必须与代码一致。

Dim dtLogin As System.Data.DataTable
    Dim userDetails As New dsMembersTableAdapters.mi_membersTableAdapter
    Dim rowsLogin As System.Data.DataRow

    'Fill datatable using method from dataset
    dtLogin = userDetails.GetUserData()

    'Find cotrols hidden in Login View
    Dim user As String = txtUser.Text
    Dim pass As String = txtPass.Text

    'Search all users
    For Each rowsLogin In dtLogin.Rows
        'Find Username Entered
        If user = dtLogin.Rows.Item(0).Item(1) Then
            'Checks users password matches
            If pass = dtLogin.Rows.Item(0).Item(2) Then
                If dtLogin.Rows.Item(0).Item(6) = 1 Then
                    'Log User In
                    FormsAuthentication.RedirectFromLoginPage(dtLogin.Rows.Item(0).Item(1), True)
                Else
                    'Account Not Active Message
                    lblValidation.Text = "There is a problem with your account, please contact the website administration"
                End If
            Else
                'Incorrect Password Message
                lblValidation.Text = "Incorrect Password"
            End If
        Else
            'No User in DB Message
            lblValidation.Text = "No User Found" + dtLogin.Rows.Item(0).Item(1)
        End If
    Next

如果有人可以提供任何帮助或指向我直接的rihgt那将是太棒了!在此先感谢:)

3 个答案:

答案 0 :(得分:1)

当您使用For Each rowsLogin In dtLogin.Rows时,您告诉编译器,对于每个dtLogin.Rows项,将其分配给变量rowsLogin

因此,每次在循环内部,您都会停止使用dtLogin.Rows.Item(0).Item(2) If pass = dtLogin.Rows.Item(0).Item(2) Then,而不是If pass = rowsLogin.Item(0).Item(2) Then

答案 1 :(得分:0)

dtLogin.Rows.Item(0).Item(1) - Rows.Item之后的(0)引用行集合中的索引,因此您总是在查看第一行。

不要在循环中使用dtLogin.Rows.Item(0).Item(1)等,而是使用rowsLogin.Item(1)

答案 2 :(得分:0)

dim bUserFound as boolean = false       
For Each rowsLogin In dtLogin.Rows
            'Find Username Entered
            If user = rowsLogin(1) Then
bUserFound = true
                'Checks users password matches
                If pass = rowsLogin(2) Then
                    If rowsLogin(6) = 1 Then
                        'Log User In
                        FormsAuthentication.RedirectFromLoginPage(rowsLogin(1), True)
                    Else
                        'Account Not Active Message
                        lblValidation.Text = "There is a problem with your account, please contact the website administration"
                    End If
                Else
                    'Incorrect Password Message
                    lblValidation.Text = "Incorrect Password"
                End If
            Else
                'No User in DB Message
               ' lblValidation.Text = "No User Found" + rowsLogin(1)

            End If
        Next 

if not bUserFound then
lblValidation.Text = "No User Found"
end if

您应该使用更清晰的代码 rowsLogin(“USER_NAME”)而不是rowsLogin(1), rowsLogin(“USER_PWD”)而不是rowsLogin(2)等