System.Data.dll中发生'System.InvalidOperationException'

时间:2018-04-16 16:33:13

标签: vb.net oledb

我正在为连接到访问数据库的Visual Basic做一个简单的登录页面,并且在运行项目时我一直收到此错误。
如果有人能帮我解决这个问题,我将不胜感激。

Imports System.Data.OleDb

Public Class frmLogin

    Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Login.accdb")
    Dim objDA As New OleDb.OleDbDataAdapter("SELECT * FROM User", objConnection)

    Dim objCB As New OleDb.OleDbCommandBuilder(objDA)
    Dim objDS As New DataSet()
    Public Username, Password As String
    Dim UserFound As Boolean

    Private Sub frmLogin_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Retrieve()
    End Sub

    Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
        Username = txtUser.Text
        Password = txtPassword.Text

        For i As Integer = 1 To (objDS.Tables("User").Rows.Count)

            If CStr(objDS.Tables("User").Rows(i - 1).Item("Username")) =
           Username And
            CStr(objDS.Tables("User").Rows(i - 1).Item("Password")) = Password Then
                UserFound = True
                Me.Hide()
                MessageBox.Show("Welcome to the System!")
                frmStudents.Show()
                Exit For
            End If
            txtUser.Text = String.Empty
            txtPassword.Text = String.Empty
        Next
        If UserFound = False Then
            MessageBox.Show("Access Denied")
        End If
    End Sub

    Private Sub Retrieve()
        objDS.Clear()
        objDA.FillSchema(objDS, SchemaType.Source, "User")
        objDA.Fill(objDS, "User")
    End Sub
End Class

此行中出现错误:

  

objDA.FillSchema(objDS,SchemaType.Source,“User”)“User”是   错误下划线

这是有关错误的进一步信息:

  

发生了类型为“System.InvalidCastException”的未处理异常   在Microsoft.VisualBasic.dll中其他信息:转换自   字符串“User”键入'Integer'无效

1 个答案:

答案 0 :(得分:0)

而不是拖拽整个用户表只是为了验证用户获得匹配的记录数。当然,在实际应用程序中,您永远不会将密码存储为纯文本。

Private Sub VerifyUser()
        Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=Login.accdb")
        Dim cmd As New OleDbCommand("Select Count(*) From Users Where [Username] = @Username and [Passwor] = @Password;", objConnection)
        cmd.Parameters.Add("@Username", OleDbType.VarChar).Value = txtUsername.Text
        cmd.Parameters.Add("@Password", OleDbType.VarChar).Value = txtPassword.Test
        objConnection.Open()
        Dim count As Integer = CInt(cmd.ExecuteScalar())
        Dim message As String = ""
        If count > 0 Then
            message = "Welcome"
        Else
            message = "Sorry"
        End If
        MessageBox.Show(message)
    End Sub