0

I'm trying to create a Login Form using Visual Basic 2015 in Visual Studio. I've followed the instructions from a video that I've watched, however, an error occurred when I tried to run the code.

Here's the codes I've done so far:


Private Sub picgo1_Click(sender As Object, e As EventArgs) Handles picgo1.Click

 openConn()

        Dim dr As SqlDataReader
        Dim cmd As SqlCommand
        Dim sqlsyntax As String
        cmd = New SqlCommand
        cmd.CommandType = CommandType.Text
        cmd.Connection = conn
        sqlsyntax = "select * from tblusers where user = '" & txtuser.Text & "' and pass = '" & txtpass.Text & "'"
        cmd.CommandText = sqlsyntax
        dr = cmd.ExecuteReader()

If dr.HasRows Then

 MsgBox("Access Granted! Welcome '" & txtuser.Text & "'")

Else

 MsgBox("Access Denied! Incorrect Username or Password!")

End If

 conn.Close()

 cmd.Dispose()

    End Sub

Another for Module

Imports System.Data.SqlClient

Module ModuleConnections
    Public conn As SqlConnection

    Sub openConn()
        Try
            conn = New SqlConnection("Data Source=E:\HRIMS\HRIMS V1.0\WINDOWSAPPLICATION2\HRIMSDB.MDF;Integrated security=True")
            If conn.State = ConnectionState.Closed Then
                conn.Open()
            End If
        Catch ex As Exception
            MsgBox("Connecting to Database Failed" & ex.ToString)
        End Try
    End Sub

End Module

When I tried to run the form, here is the error I'm getting. Then when I pressed ok, it points me to this line.

I'm still trying to learn, so please don't be too hard on me :D

Thank you in advance.

Maciej Los
  • 8,468
  • 1
  • 20
  • 35
  • Did you also copy the connection string (conn= New SqlConnection...) from the video or is it pointing to your own DB? – ehh Aug 03 '16 at 05:54
  • @ehh, that was mine. This part specifically "E:\HRIMS\HRIMS V1.0\WINDOWSAPPLICATION2\HRIMSDB.MDF". The rest are copied from the video. – Kelvin Jhon Aug 03 '16 at 05:58
  • @Luke, I got that, however, I don't know what's wrong. I was able to create my database without any errors. The tables are ready as well so I have no idea what to do next. Is this line "conn = New SqlConnection("Data Source=E:\HRIMS\HRIMS V1.0\WINDOWSAPPLICATION2\HRIMSDB.MDF;Integrated security=True")" my main issue? What should link should I put for the data source? Thank you. – Kelvin Jhon Aug 03 '16 at 06:11
  • Haven't used .mdf databases yet. I'd always suggest to use SQL databases (for example SQL EXPRESS), but that's a different topic. Have you tried using a username/password and checked the file-permissions yet? Also you are using a space in your filepath - tried removing it? It might causes the error. – Luke Aug 03 '16 at 06:16
  • How did you create that database? an MDF file is a SQL Server data file. Looks to me like your connection string is incorrect. – Jeroen Aug 03 '16 at 06:18
  • I can't see your error message but its not clear what provider you are using and which version of SQL express you are using. I recommend looking at this article: https://msdn.microsoft.com/en-us/library/hh510202(v=sql.110).aspx – Haim Katz Aug 03 '16 at 06:23
  • Btw. I'd highly recommend not using msgbox/Messagebox for showing exceptions; The user has almost no way to save the message which will make it a lot harder for you to ever track down errors in the future. – Luke Aug 03 '16 at 06:31
  • @HaimKatz, here are the information that may help you with regard to my databases. This is the [database](https://postimg.org/image/l3krv6utt/) I've used when I created it. And this is how it looks like when it is viewed in SQL Server Object Explorer [Here](https://postimg.org/image/s82l48235/). I hope this is what you meant with regard to the provider. I hope these images helped. – Kelvin Jhon Aug 03 '16 at 06:32
  • @Jeroen, I followed a video about adding a database connection. Project > add new item > data > service-based database. I think my problem is the connection string too. Which I have no idea how to fix :/ – Kelvin Jhon Aug 03 '16 at 06:34
  • @HaimKatz, I would also like to point out that I haven't installed any sql type of software. Just the whole Visual Studio community 2015. – Kelvin Jhon Aug 03 '16 at 06:36
  • 2
    Your connection string is flat out wrong. MDF files are no use on their own. They have to be attached to a SQL Server instance of some sort, be it full, Express or LocalDB. I don't know but I would guess that LocalDB is installed with VS. Go to www.connectionstrings.com to learn how to write a SQL Server connection string. – jmcilhinney Aug 03 '16 at 06:43
  • @jmcilhinney, thank you for that information. My problem is I have no idea as to how I can attached my MDF to an SQL server. Also, I'm having trouble understanding my server connection. Very sorry. – Kelvin Jhon Aug 03 '16 at 07:10
  • http://stackoverflow.com/questions/8926512/how-do-i-connect-to-an-mdf-database-file This may help you – ehh Aug 03 '16 at 07:49
  • @ehh, changed my connection string into [this](https://postimg.org/image/u6ox0tes7/). Still with the same error. – Kelvin Jhon Aug 03 '16 at 08:10
  • You should still try removing the blank spaces from the filepath. Even if the connectionstring is correct, a space inside a filepath can lead to errors. When ever you are coding or setting up a system avoid blanks in file and folder names. – Luke Aug 03 '16 at 08:25
  • If you used a service-based database, this may be of help: http://stackoverflow.com/questions/27697963/connecting-to-a-service-based-datasource-in-c-sharp – Jeroen Aug 03 '16 at 21:54

1 Answers1

0

Try:

Public conn As SqlConnection

Public Sub openConn()
        conn = New SqlConnection(CONNECTIONSTRING)
        If conn.State = ConnectionState.Closed Then
            conn.Open()
        End If
        Return conn
End Function

Login code:

 Using cmd As New SqlCommand("SELECT * 
                             FROM tblusers 
                             WHERE user = @userName 
                             AND pass = @userPass", openConn)
   'Parameterize your query to be safe from SQL Injection
   cmd.Parameters.AddWithValue("@userName", txtuser.Text)
   cmd.Parameters.AddWithValue("@userPass", txtpass.Text)
   Using rdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleResult)
       Dim Login As Object = 0
       If rdr.HasRows Then
           rdr.Read
           Login = rdr(Login)
       End If
       If Login = Nothing Then
           MsgBox("Access Denied! Incorrect Username or Password!")
       Else
           'MsgBox("Access Granted! Welcome '" & txtuser.Text & "'")
           MsgBox(String.Format("Access Granted! Welcome {0}!", txtuser.text)
       End If
    End Using
End Using
  • The OP has a problem with the connection string. You just removed the offending connection string, how is that going to help? – Jeroen Aug 03 '16 at 21:59
  • @Jeroen, thanks for that info bro. My laptop was pulled out yesterday for warranty. Suddenly died for no reason so I haven't had the chance to do the instructions on the link you've provided. I will get back to you once I got my laptop back. Thank you again. – Kelvin Jhon Aug 05 '16 at 00:55