【问题标题】:Assign Gridview DropDownList Value分配 Gridview DropDownList 值
【发布时间】:2016-10-30 21:42:48
【问题描述】:

我需要 DropDownList ddlReceipt 来显示数据库中的值。我当前的代码如下。

我感觉我的代码在 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();
}

【问题讨论】:

    标签: c# sql asp.net gridview


    【解决方案1】:

    您错过了大部分代码。您必须从 DB 中读取数据(这就是您创建 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      相关资源
      最近更新 更多