简体   繁体   English

Asp 下拉列表不返回选定的值。 (下拉列表是数据绑定的)

[英]Asp Dropdownlist does not return selected value. (Dropdownlist is Databound)

I have created a dropdownlist, which loads its data from a table column.我创建了一个下拉列表,它从表列加载数据。 Now I want to select the value of dropdownlist on Index_change_event .现在我想在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;
    }
}

Remove if (!IsPostBack) from DropDownList1_SelectedIndexChanged event and if (!IsPostBack) should be on Page_Load event.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();
     }
}

You are only checking !IsPostBack.您只是在检查 !IsPostBack。 As the event is firing from a postback this will never be run.由于事件是从回发中触发的,因此永远不会运行。 Also, be careful that you are not re-binding the datasource and therefore changing the selected value on page_load.此外,请注意不要重新绑定数据源并因此更改 page_load 上的选定值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM