2016-04-11 69 views
0

我不知道哪裏出了問題。我新來到vb。有人能幫我嗎?也許糾正我的代碼,因爲我一直花這麼多時間用這個登錄表單。謝謝!這是我的代碼。順便說一句,我有一個3列的表。用戶名,密碼和特權。無論何時輸入我的登錄憑據,它只會顯示Msgbox再次嘗試。VB.net用MySQL登錄

Imports MySql.Data.MySqlClient 
Public Class LoginForm 
    Dim cn As New MySqlConnection 
    Dim cmd As MySqlCommand 
    Dim reader As MySqlDataAdapter 

    Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click 
     Dim tblUser As New DataTable 

     Try 
      If PasswordTextBox.Text = "" Or UsernameTextBox.Text = "" Then 
       MessageBox.Show("Please provide your login credentials!") 
      Else 
       Dim sql As String 
       sql = "SELECT * from user_account where username = '" & UsernameTextBox.Text & "' and password = '" & PasswordTextBox.Text & "'" 

       Using con As New MySqlConnection(My.Settings.ConnectionString) 
        With cmd 
         .Connection = con 
         .CommandText = sql 
        End With 

        reader.SelectCommand = cmd 
        reader.Fill(tblUser) 

        If tblUser.Rows.Count > 0 Then 
         Dim userType As String 
         userType = tblUser.Rows(0).Item(2) 

         If userType = "admin" Then 
          MsgBox("Welcome, Admin!") 
          frmAdminMain.Show() 
         ElseIf userType = "encoder" Then 
          MsgBox("Welcome, User!") 
          MainForm.Show() 
         End If 
        Else 
         MsgBox("Invalid Credentials!") 
        End If 
        reader.Dispose() 
       End Using 
      End If 
     Catch ex As Exception 
      MsgBox("Try Again!") 
     End Try 
    End Sub 

回答

0

「新」關鍵字添加到您的命令聲明

Dim cmd As New MySqlCommand 

「與」剛設置的屬性,它不初始化的對象。

+0

我會剛剛發送我的答案像評論,但我需要更多的聲譽。 –

+0

我只是要將MsgBox(ex.ToString)粘貼到catch部分? – noob

+0

它說,System.NullReferenceException:對象引用未設置爲在WindowsApplication1對象的實例... vb:第19行 而第19行是.Connection = con – noob