我已经在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
答案 0 :(得分:1)
我的猜测是你没有Option Strict On,而且你的Try / Catch块的Try部分正在创建dr。当你到达Finally部分时,它超出了范围。您也可以通过在catch块中没有throw语句来吞下您可能遇到的任何错误。
尝试:
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和Option Explicit声明的其他链接
http://www.readmespot.com/question/o/222370/option-strict-on-and--net-for-vb6-programmers
杰夫阿特伍德的编码恐怖article
答案 1 :(得分:1)
这样:
TextBox1.Text = userid
TextBox2.Text = password
看起来不对。除此之外,你可能没有在阅读器上获得任何记录(因为那条线)..这就是为什么你没有得到任何结果。无论如何在finally块上使用它是浪费开销。
你的SQL也错了,它有a)超过需要的
答案 2 :(得分:1)
使用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