【问题标题】:How to set dropdown list value and item as database table value in edit?如何在编辑中将下拉列表值和项目设置为数据库表值?
【发布时间】:2013-05-06 06:30:11
【问题描述】:

当我点击编辑按钮时,文本框和下拉列表中的表单填充数据库值..

文本框值已设置。但我无法设置下拉列表值..

代码是;

SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string str = "Select * from Master where Id='" + id + "'";
SqlCommand command = new SqlCommand(str, con);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
      ddCustomerName.DataValueField = reader["CustomerId"].ToString();
      txtPickupLocation.Text = reader["Location"].ToString();
}
con.Close();   

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您必须在列表中选择 CustomerId,为此您必须编写

    ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected=true;
    

    而不是

     ddCustomerName.DataValueField = reader["CustomerId"].ToString();
    

    【讨论】:

      【解决方案2】:

      嘿,Saranya 之前的帖子是完美的,但是如果 Dropdown 值与 DB 值不匹配,或者 Dropdown 没有 Db 返回的值,它会给出错误,因此更安全的一面总是检查 null 值。

      请使用此代码

      if (ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()) != null)
              dddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected = true;
      

      【讨论】:

        【解决方案3】:
        use selectedvalue property
        
        while (reader.Read())
        {
            ddCustomerName.SelectedValue= reader["CustomerId"].ToString();
            txtPickupLocation.Text = reader["Location"].ToString();
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-01-24
          • 1970-01-01
          • 1970-01-01
          • 2021-04-04
          • 2017-05-31
          • 2016-07-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多