Search code examples
c#sqlasp.netdata-binding

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;
    }
}

Solution

  • 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();
         }
    }