Parth Doshi
Parth Doshi

Reputation: 4208

Validate user using windows form and SQL database

I have a windows form that takes username and password. It validates it with the database I have created that contains the correct usernames and passwords. So I have implemented a code to verify whether the details entered are proper

Here is my code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
        myconnection = New SqlConnection("server=PARTH-PC\SQLEXPRESS;uid=sa;pwd=demo;database=fc")
        'you need to provide password for sql server
        myconnection.Open()
        TextBox1.Text = userid
        TextBox2.Text = password



        mycommand = New SqlCommand("select * from student where user id='" & TextBox1.Text & "' and password='" & TextBox2.Text & "')", myconnection)
    Catch ex As Exception
    Finally

    End Try

    Try


        If EOF(1) Then

            MessageBox.Show("Access Denied...Please enter correct password!")

            TextBox1.Text = ""

            TextBox2.Text = ""

            'txtUserName.SetFocus()




        Else
            Txt = "" & " " & UCase$(TextBox1.Text) & ""
            MsgBox("Welcome!!!" & Txt)
            Form2.Show()
        End If
    Catch ex As Exception

    End Try

    myconnection.Close()
     End Sub
  End Class

I am facing a problem in this code..its not working fine ..can someone help me

Upvotes: 0

Views: 4417

Answers (1)

John Gathogo
John Gathogo

Reputation: 4665

Without going into the many cons of your code and how you are going about authenticating your users, you could correct your code as follows:

myconnection.Open();
mycommand = new SqlCommand("select * from student where user id='" & TextBox1.Text & "' and password='" & TextBox2.Text & "')", myconnection)
SqlDataReader reader = mycommand.ExecuteReader();
if(reader != null) 
{
    if(reader.Read())
    {
        // You found your user. Do what you need to do here.
    }
    else
    {
        // You did not find your user. Do what you need to do here.
    }
}
else
{
    // Something went wrong. You did not find your user. Do what you need to do here.
}

NOTE: The code is in C#. It shouldn't be difficult to change it into its VB.NET equivalent

Upvotes: 1

Related Questions