我怎样才能在vb.net中修复此错误?你调用的对象是空的

时间:2018-03-14 04:57:24

标签: vb.net

Imports System.Data.SqlClient
Public Class Admin
    Dim cn As SqlConnection
    Dim cmd As SqlCommand
    Dim rdr As SqlDataReader
    Dim cs As String = "Data Source = RYAN-PC\SQLEXPRESS;Initial Catlog=jtwinsgarment;Integrated Security =true"

    Private Sub login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles login.Click
        Try
            cn.Open()
            cmd.CommandText = "select from adminsaccount where UserAdmin='" + TextBox1.Text = "' and PassAdmin ='" + TextBox2.Text + "'"
            rdr = cmd.ExecuteReader()
            If rdr.Read() Then
                AdminsHome.Show()
            Else
                MessageBox.Show("Invalid User Details....")

            End If
            cn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString())
        Finally
            cn.Close()

        End Try
    End Sub

    Private Sub Admin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            cn = New SqlConnection(cs)
            cmd = New SqlCommand(cs, cn)
            cn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString())
        Finally
            cn.Close()

        End Try
    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

cmd = new SQLCommand(cs, cn)存在问题此构造函数接受一个字符串,该字符串是查询字符串和连接对象。您已传入连接字符串。修复如下

cmd = New SQLCommand()
cmd.Connection = cn

此外,不使用字符串连接来构建SQL查询非常重要。学习使用参数并始终执行。 不确定为什么要在表单加载中关闭连接。你永远不会打开它。创建连接对象与打开它不同。