当我单击编辑按钮时,文本框中的表单填充数据库值以及下拉列表..
设置了文本框值。但我无法设置下拉列表值..
代码是;
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();
答案 0 :(得分:2)
您必须在列表中选择CustomerId,因为您必须编写
ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected=true;
而不是
ddCustomerName.DataValueField = reader["CustomerId"].ToString();
答案 1 :(得分:2)
Hey Saranya之前的帖子很完美,但是如果Dropdown值与DB值不匹配或Dropdown没有值Db返回值,则会出错,所以更安全的方也总是检查空值。
请使用此代码
if (ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()) != null)
dddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected = true;
答案 2 :(得分:1)
use selectedvalue property
while (reader.Read())
{
ddCustomerName.SelectedValue= reader["CustomerId"].ToString();
txtPickupLocation.Text = reader["Location"].ToString();
}