简体   繁体   中英

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 .

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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