在为变量“ loginusername”分配值之前,先使用该变量。空引用异常可能在运行时导致

时间:2019-05-02 08:16:37

标签: vb.net visual-studio-2017

我收到一个错误消息,说字符串没有值。但是我已经分配了一个值,但是不知何故我看不到一个错误。请帮忙。

  

在为其分配值之前使用变量'loginusername'。   空引用异常可能会在运行时导致。

     

在为其分配值之前使用变量“ loginpword”。一种   空引用异常可能在运行时导致。

当我更改loginusername和loginpword的数据类型时,错误消失了,但是我需要将其设置为字符串数据类型。

        Dim strFile As String = "D:\DBSystem\Connection\connconfig.dbs"
        Dim sr As New IO.StreamReader(strFile)
        Dim ip As String
        Dim port As String
        Dim userid As String
        Dim password As String
        Dim database As String

        'reading
        ip = sr.ReadLine()
        port = sr.ReadLine()
        userid = sr.ReadLine()
        password = sr.ReadLine()
        database = sr.ReadLine()
        sr.Close()


        'default connection code
        Dim serverstring As String = "server=" & ip & ";port=" & port & ";database=" & database & ";user ID=" & userid & ";password=" & password & ";OldGuids=true"
        Dim sqlconnection As MySqlConnection = New MySqlConnection
        sqlconnection.ConnectionString = serverstring
        Dim Reader As MySqlDataReader
        Dim loginpword As String
        Dim loginusername As String

        Try
            If sqlconnection.State = ConnectionState.Closed Then
                sqlconnection.Open()
                Dim sqlstatement As String = "SELECT Username,Password FROM SDS_Users WHERE `Username` =' " & Login_tb_username.Text & "'"
                Dim Command = New MySqlCommand(sqlstatement, sqlconnection)
                Reader = Command.ExecuteReader

                While Reader.Read
                    loginpword = Reader.GetString("Password")
                    loginusername = Reader.GetString("Username")

                End While

                Reader.Close()

                If Login_tb_username.Text = loginusername And Login_tb_password.Text = loginpword Then
                    Me.Visible = False
                    Main_window.Visible = True
                    sqlconnection.Close()
                Else
                    MessageBox.Show("Username & Password doesn't match any account!", "Error",
                   MessageBoxButtons.OK)
                End If
            Else
                sqlconnection.Close()
                MsgBox("Connection Error!", "Error")

            End If

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

1 个答案:

答案 0 :(得分:5)

您正在以下代码块中为变量分配值:

While Reader.Read
    loginpword = Reader.GetString("Password")
    loginusername = Reader.GetString("Username")
End While

由于Reader是数据库查询的结果,因此不能保证包含值。 While块的内容可能无法执行,因此会出现错误。

要解决此错误,只需使用默认/初始值初始化变量,例如:

Dim loginpword As String = ""
Dim loginusername As String = ""