![](/img/trans.png)
[英]SelectetValue does not return the selected value in ASP.NET DropDownList
[英]Asp Dropdownlist does not return selected value. (Dropdownlist is Databound)
我創建了一個下拉列表,它從表列加載數據。 現在我想在Index_change_event
上選擇 dropdownlist 的值。
protected void Page_Load(object sender, EventArgs e)
{
string username = Session["username"].ToString();
SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
string query = "select Fence_Name from Fence where Username='" + username + "'";
SqlCommand command = new SqlCommand(query, con);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataValueField = "Fence_Name";
DropDownList1.DataTextField = "Fence_Name";
DropDownList1.DataBind();
con.Close();
//arr = Session["arr"].ToString();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label2.Text = DropDownList1.SelectedItem.Value;
}
}
從DropDownList1_SelectedIndexChanged
事件中刪除if (!IsPostBack)
和if (!IsPostBack)
應該在Page_Load
事件上。
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DropDownList1.SelectedItem.Value;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string username = Session["username"].ToString();
SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
string query = "select Fence_Name from Fence where Username='" + username + "'";
SqlCommand command = new SqlCommand(query, con);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataValueField = "Fence_Name";
DropDownList1.DataTextField = "Fence_Name";
DropDownList1.DataBind();
con.Close();
}
}
您只是在檢查 !IsPostBack。 由於事件是從回發中觸發的,因此永遠不會運行。 此外,請注意不要重新綁定數據源並因此更改 page_load 上的選定值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.