Проверка пользователя в VB.NET - PullRequest
0 голосов
/ 21 октября 2011

Я реализовал код для проверки пользователя в VB.NET. Когда я ввожу имя пользователя и пароль в текстовые поля своей формы и нажимаю кнопку отправки, окно сообщения не отображается, даже если я написал для него код. Есть ли какая-то проблема в блоке try-catch или я пропустил несколько строк кода?

Может кто-нибудь указать, что не так в этом коде?

       Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As  System.EventArgs) Handles Button1.Click

    If TextBox1.Text = "" Or TextBox2.Text = " " Then
        MsgBox("Enter a user id and password")
    End If
    TextBox1.Text = userid
    TextBox2.Text = password

    Try
        myconnection = New SqlConnection("server=PARTH-PC\SQLEXPRESS;uid=sa;pwd=demo;database=fc")
        'you need to provide password for sql server
        myconnection.Open()

        mycommand = New SqlCommand("select * from student where user id='" &  TextBox1.Text & "' and password='" & TextBox2.Text & "')", myconnection)
        dr = mycommand.ExecuteReader()

    Catch ex As Exception
    Finally



        If (dr IsNot Nothing) Then

            If (dr.Read()) Then

                MsgBox("User is authenticated")
                Form2.Show()



            Else
                MsgBox("Please enter correct username and password")
            End If


        End If

    End Try

    myconnection.Close()
      End Sub
    End Class

Ответы [ 3 ]

1 голос
/ 21 октября 2011

это:

TextBox1.Text = userid
TextBox2.Text = password

выглядит неправильно.кроме того, вы, вероятно, не получаете никакой записи на читателя (из-за этих строк) ... и именно поэтому вы не получаете никакого результата.В любом случае, использование этого в блоке finally является пустой тратой накладных расходов.

Кроме того, ваш SQL неверен, он имеет а) больше, чем необходимо

1 голос
/ 21 октября 2011

Используйте Trim() и Length методы или String.IsNullOrWhiteSpace() (.net framework 4) для проверки пустой строки или строки нулевой длины.

 If TextBox1.Text.Trim().Length = 0 Or TextBox2.Text.Trim().Length = 0 Then
   MsgBox("Enter a user id and password")
   Return 'Terminate this method
 End If

Неправильное назначение здесь,

 Dim userid=TextBox1.Text
 Dim password=TextBox2.Text

Другая проблема заключается в использовании жестко закодированного оператора SQL.

myconnection = New SqlConnection("server=PARTH-PC\SQLEXPRESS;uid=sa;pwd=demo;database=fc")
mycommand = New SqlCommand("select * from student where [user id]=@userid and [password]=@password",myconnection)
mycommand.Parameters.Add("@userid",SqlDbType.VarChar,30).Value = userid
mycommand.Parameters.Add("@password",SqlDbType.VarChar,30).Value = password

myconnection.Open()
dr = mycommand.ExecuteReader()
Dim isFound as boolean  = false
if dr.Read() Then
   isFound=true
End If
dr.Close()
myConnection.Close()

if IsFound Then
   MsgBox("User is authenticated")
   Form2.Show()
Else
   MsgBox("Please enter correct username and password")
End If
1 голос
/ 21 октября 2011

Я предполагаю, что у вас нет Option Strict On, и dr создается в части Try вашего блока Try / Catch.Это выходит за рамки, когда вы попадаете в раздел «Наконец».Вы также проглатываете любые ошибки, которые могут у вас возникнуть, если в вашем блоке перехвата нет оператора throw.

Try:

Dim myconnection as SqlConnection
Dim mycommand as SqlCommand
Dim dr as SqlDataReader
Try 
    myconnection = New SqlConnection("server=PARTH-PC\SQLEXPRESS;uid=sa;pwd=demo;database=fc") 
        'you need to provide password for sql server 
    myconnection.Open() 

    mycommand = New SqlCommand("select * from student where user id='" &  TextBox1.Text & "' and password='" & TextBox2.Text & "')", myconnection) 
    dr = mycommand.ExecuteReader() 

Catch ex As Exception 
    Throw
Finally 
    If (dr IsNot Nothing) Then 
        If (dr.Read()) Then 
            MsgBox("User is authenticated") 
            Form2.Show() 
        Else 
            MsgBox("Please enter correct username and password") 
        End If 
    End If 

End Try 

myconnection.Close() 

Редактировать: Дополнительные ссылки для Option Strict и Опция Явный операторы

http://www.readmespot.com/question/o/222370/option-strict-on-and--net-for-vb6-programmers

И код ужаса статья Джеффа Этвуда

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...