2011-12-31 63 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

相關問題