2011-12-31 66 views
0

我可以在如何从数据库检索记录的工作示例中选择下拉列表后填充相关文本框。我有什么是绝对不工作&即时通讯工作VS 2008。任何人都可以告诉我的方式?从下拉列表中选择后,从SQL查询中填充文本框

我有:

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() 

回答

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 

这仅仅是一个简单的例子,并且不包含错误处理,但应该工作。

+0

就是这样!非常感谢! :) – brainsfrying 2012-01-01 08:05:39

相关问题