2011-12-31 10 views
0

DBからレコードを取得する方法についてのサンプルがあります。&ドロップダウンリストで選択した後に関連するテキストボックスにデータを入力してください。私が持っているものは間違いなく働いていません&私は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

関連する問題