How may I correctly assign textboxes, dropdownlists & labels to appropriate fields, on successful retrieval of records via a SQL statement? I have 4 tables & therefore, the assigned data don’t match the controls. (VS2008)
I have the following:
myCmd.CommandText = "SELECT pc.product_category_id, pc.product_category_name, pi.product_image_id, pi.product_image_filename, qr.qrcode_id, qr.qrcode_image_filename, p.product_author FROM Product AS p INNER JOIN ProductCategory AS pc ON p.product_category_id = pc.product_category_id INNER JOIN ProductImage AS pi ON p.product_image_id = pi.product_image_id INNER JOIN QRCode AS qr ON p.qrcode_id = qr.qrcode_id WHERE p.product_id = '" & DropDownList2.Text & "'"
myCmd.Parameters.Add(New SqlParameter("@product_id", (DropDownList2.Text)))
myConn.Open()
'run the query and obtain a reader to get the results
dtrReader = myCmd.ExecuteReader()
'check if there are results
If (dtrReader.Read()) Then
'populate the values of the controls
lblProductID2.Text = dtrReader(0)
txtProductName2.Text = dtrReader(4)
txtProductTitle2.Text = dtrReader(7)
txtProductDescription2.Text = dtrReader(8)
txtProductAuthor2.Text = dtrReader(12)
There are at least two ways to solve this:
1) Explicitly use the names of the columns when retrieving from datareader:
2) Cycle through each of the fields in the reader and use a case statement to assign values
Number 2 is probably slightly better because it makes it easier to test for DBNull values in the returned data: