2016-06-28 47 views
1

我需要DropDownList ddlReceipt來顯示數據庫中的值。我目前的代碼如下。Assign Gridvew DropDownList值

我有一種感覺,我的代碼是錯誤的ddlReceipt.SelectedValue =「toa_receipt」;但我並不確定。

foreach (GridViewRow row in gvCreditCards.Rows) 
     { 
      DropDownList ddlReceipt = row.FindControl("ddlReceipt") as DropDownList; 
      string id = row.Cells[0].Text; 
      SqlConnection con2 = new SqlConnection(conStringTOA); 
      SqlDataAdapter sda2 = new SqlDataAdapter(); 
      SqlCommand cmd2 = new SqlCommand("SELECT toa_receipt FROM toa_CreditCardStatement WHERE id = '" + id + "'"); 
      cmd2.Connection = con2; 
      con2.Open(); 
      ddlReceipt.SelectedValue = "toa_receipt"; 
      con2.Close(); 
     } 

回答

1

您錯過了很好的一部分代碼。你必須從數據庫讀取數據(這就是你創建SqlCommand的原因)。

//your code 
//SqlDataAdapter sda2 = new SqlDataAdapter();//no need 
SqlCommand cmd2 = new SqlCommand("SELECT toa_receipt FROM toa_CreditCardStatement WHERE id = @id", con2); 
//It is very insecure to concatenate value into SQL string 
//cmd2.Connection = con2; 
//Use parameter instead 
cmd2.Parameters.Add("@id",DbType.VarChar).Value = id; 
con2.Open(); 
using(SqlDataReader r = cmd2.ExecuteReader()){ 
    if(r.Read()){ 
     ddlReceipt.SelectedValue = (string)r["toa_receipt"]; 
    } 
r.Close(); 
} 
con2.Close(); 
+0

謝謝!!!我改變它,它完美的工作! – MMoore94