0

May i have a working sample on how to retrieve records from a DB & populate the relevant textboxes after a selection at a dropdownlist. What i have is definitely not working & im working on VS 2008. Can anyone show me the way?

What i have:

    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 Answer 1

2

The parameters collection of the command is to pass parameters to the query and not fill in variables from a result. First you should do the query and then read the results and fill your controls:

' 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

This is just a quick example and contains no error handling but should work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.