-1
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
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
  • Without details it is hard to predict where this error happen ? At which line did you get this exception ? – NeverHopeless Mar 14 '18 at 05:05
  • Here: `Dim cn As SqlConnection` is declared. Then on `login_Click` event you opened the connection `cn.Open` without creating a new instance of the object. i **guess** this is it. – kiLLua Mar 14 '18 at 05:25
  • @kiLLua I believe he creates an instance in the Form.Load – Mary Mar 14 '18 at 06:01
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – jmcilhinney Mar 14 '18 at 06:02
  • Please tell us what line the exception occurred on and provide a stack trace of the exception. – Chris Dunaway Mar 14 '18 at 13:46

1 Answers1

0

There is a problem with cmd = new SQLCommand(cs, cn) This constructor takes a string which is the query string and a connection object. You have passed in the connection string. Fix it as follows

cmd = New SQLCommand()
cmd.Connection = cn

Also, it is very important that you not use string concatenation to build SQL queries. Learn to use Parameters and do it always. Not sure why you are closing your connection in the form load. You never opened it. Creating a connection object is not the same as opening it.

Mary
  • 14,926
  • 3
  • 18
  • 27