简单的登录表单错误VB 2010

时间:2018-05-06 01:48:15

标签: vb.net

我搜索了很多资源而无法修复它。 我的问题是当我点击按钮事件时,下一个表单没有显示,我也想同时关闭我的登录表单。

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   Dim firstname As String = ""
    Dim lastname As String = ""
    Dim ara As Boolean = False
    cn = New OleDbConnection(con)
    cn.Open()
    Dim user As String
    Dim pass As String
    user = TextBox1.Text
    pass = TextBox2.Text
    With cmd
        .Connection = cn
        .CommandText = "Select * from users WHERE username='" & user & "' AND password='" & pass & "'"
        .ExecuteNonQuery()
        rdr = cmd.ExecuteReader
        If rdr.HasRows Then
            ara = True
            While rdr.Read()

                firstname = rdr("firstname").ToString
                lastname = rdr("lastname").ToString

                lib_name = firstname + lastname
            End While

            If ara = True Then

                Form2.Show()
                Me.Close()
                x = True

            Else
                MsgBox("  Access Denied!" + Environment.NewLine + "Sorry, username or password is incorrect!")
            End If
        End If
    End With

    cn.Close()
    cmd.Dispose()

1 个答案:

答案 0 :(得分:0)

1:您正在打开 SQL INJECTION 的大门。 Read more。不是直接在查询中传递值,而是先传递参数并在以后使用它们(原因不明,代码格式化不起作用):

Dim cmd as New OleDbCommand("Select * from users WHERE username=@user AND password=@pass" , con)
With cmd

.Parameters.Add("@user", OleDbType.Varchar).Value = user

.Parameters.Add("@user", OleDbType.Varchar).Value = password
End With

2:您的If语句只有IDateReader.HasRows才能返回true,如果ara=True则不需要。 .HasRows是一个布尔值,您不需要创建另一个布尔值并将值传递给它。但是,只有在条件匹配时才会执行其余代码

3:Form1.CloseAnotherForm.Show如果在您的项目属性中,Shutdown Mode设置为On main window close(默认情况下),则永远不会有效。将其更改为On Explicit window closeOn last window close 更改

Me.CLose

Me.Hide

4:为了减少太多代码,您可以使用Using Statement

Using cmd as New SqlCommand("Select * from users WHERE username=@user AND password=@pass" , con)
'''codes here
End Using
''Now no need to call cmd.Dispose

希望这会有所帮助:)