2012-01-01 26 views
0

我怎麼可能正確地分配文本框,通過SQL語句dropdownlists &標籤相應的字段上的記錄檢索成功?我有4個表&因此,所分配的數據不匹配的控件。 (VS2008)正確分配數據控件,SQL服務器,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

您有一個SQL注入漏洞。 – SLaks 2012-01-01 17:56:44

+0

@SLaks:我明白你來自哪裏。謝謝,但關於這個問題,是否有一種更簡單的方法來匹配這些字段? – brainsfrying 2012-01-01 18:04:02

+0

關於您現有的代碼有哪些不正確/不足? – MatBailie 2012-01-01 18:13:53

回答

0

至少有兩種方法來解決這個問題:

1)從DataReader的檢索時,明確使用的列的名稱

lblProductID2.Text = dtrReader("product_category_id") 
' etc 

2)通過每一個在讀取器中的字段,並使用的情況下,語句週期分配值

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值:

+0

是的,我認爲應該做的工作太多。非常感激 :) – brainsfrying 2012-01-01 18:43:27