在下拉列表中选择后,从SQL查询填充文本框

时间:2011-12-31 21:22:11

标签: .net vb.net

我是否有关于如何从数据库和数据库中检索记录的工作示例?在下拉列表中选择后填充相关的文本框。我所拥有的绝对不起作用&我正在研究VS 2008.有人能告诉我这个方式吗?

我有什么:

    Dim myConn As New SqlConnection
    Dim myCmd As New SqlCommand
    Dim dtrReader As SqlDataReader

    myConn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
    myCmd = myConn.CreateCommand

    myCmd.CommandText = "SELECT * FROM Product WHERE product_id = '" & DropDownList2.Text & "'"
        'myCmd.CommandType = CommandType.Text

        'populate controls from DB
        'myCmd.Parameters.Add(New SqlParameter("@product_id", a))
        myCmd.Parameters.Add(New SqlParameter("@product_name", (txtProductName2.Text)))
        myCmd.Parameters.Add(New SqlParameter("@product_title", txtProductTitle2.Text))
        myCmd.Parameters.Add(New SqlParameter("@product_desc", txtProductDescription2.Text))
        myCmd.Parameters.Add(New SqlParameter("@product_author", txtProductAuthor2.Text))

        mycmd.Dispose()
        myConn.Close()
        myConn.Dispose()

1 个答案:

答案 0 :(得分:2)

命令的参数集合是将参数传递给查询,而不是从结果中填入变量。首先,您应该进行查询,然后阅读结果并填写控件:

' build the query with the product id as paramter
myCmd.CommandText = "SELECT product_name, product_title, product_desc, product_author FROM Product WHERE product_id = @product_id"
' add the parameter so the SqlCommand can build the final query
myCmd.Parameters.Add(New SqlParameter("@product_id", (DropDownList2.Text)))

' run the query and obtain a reader to get the results
Dim reader As SqlDataReader = myCmd.ExecuteReader()

' check if there are results
If (reader.Read()) Then
     ' populate the values of the controls
     txtProductName2.Text = reader(0)
     txtProductTitle2.Text = reader(1)
     txtProductDescription2.Text = reader(2)
     txtProductAuthor2.Text = reader(3)
End If

这只是一个快速示例,不包含错误处理,但应该可以正常工作。