如何正确分配文本框,下拉列表和&通过SQL语句成功检索记录时,标签到适当的字段?我有4张桌子和1张桌子。因此,分配的数据与控件不匹配。 (VS2008)
我有以下内容:
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)
答案 0 :(得分:0)
至少有两种方法可以解决这个问题:
1)从datareader检索时显式使用列的名称:
lblProductID2.Text = dtrReader("product_category_id")
' etc
2)遍历阅读器中的每个字段并使用case语句分配值
For nI As Integer = 0 To dtrReader.FieldCount - 1
Select Case dtrReader.GetName(nI).ToLower()
Case "product_category_id"
If Not dtrReader.IsDBNull(nI) Then
lblProductID2.Text = dtrReader.GetString(nI)
Else
lblProductID2.Text = String.Empty
End If
' etc
End Select
Next
数字2可能稍好一些,因为它可以更容易地在返回的数据中测试DBNull值: