选择后,vb.net下拉列表无法弹出详细信息

时间:2017-12-05 22:30:30

标签: sql-server vb.net

我想要做的是从下拉列表中选择名称后,可以在文本框中弹出与用户相关的详细信息。我在sql alreaday创建了一个名为VEditUser的视图。但是在我运行代码之后,尝试catch总是告诉" ="。有人能告诉我哪里出错了吗?

Dim MyConnection As New SqlConnection
Dim Command As New SqlCommand
Dim Datareader As SqlDataReader

Try

'Create a connection to the SQL server
MyConnection.ConnectionString = "server=(local);database=dbSQL1;Trusted_Connection=yes"
MyConnection.Open()
Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser = " & ddlCustomer.SelectedValue

Command.Connection = MyConnection
Datareader = Command.ExecuteReader

Try
    If Datareader.HasRows Then

        Datareader.Read()

        txtFirstName.Text = Datareader.Item("strFirstName")
        txtLastName.Text = Datareader.Item("strLastName")
        txtAddress.Text = Datareader.Item("strAddress")
        txtCity.Text = Datareader.Item("strCity")
        dpdState.Text = Datareader.Item("intStateID")
        txtZipcode.Text = Datareader.Item("strZipcode")
        txtEmail.Text = Datareader.Item("strEmail")
        txtCellPhone.Text = Datareader.Item("strCellPhone")
        dpdServiceGroup.Text = Datareader.Item("intServiceGroupID")
        dpdRole.Text = Datareader.Item("intRoleID")
        dpdStatus.Text = Datareader.Item("intStatusID")
        txtUserName.Text = Datareader.Item("strLoginName")
    End If

Catch ex As Exception

End Try

MyConnection.Close() 'Close the connection.

1 个答案:

答案 0 :(得分:0)

快速回答是您错过了Sql中的where

变化:

Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser = " & ddlCustomer.SelectedValue

Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser WHERE strLoginName  = " & ddlCustomer.SelectedValue

例如。如果strLoginName不是下拉列表中的值,则根据需要进行替换

稍微长一点的答案是,您应该通过始终清理输入并使用参数化查询来保护自己免受Sql Injection的攻击。在您提供的示例中,您可以使用以下命令实现此目的:

Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser WHERE strLoginName = @customer"

cmd.Parameters.Add("@customer", SqlDbType.VarChar, 50).Value = ddlCustomer.SelectedValue

Command.Connection = MyConnection