Search code examples
asp.netdrop-down-menuselectedvalue

Get DropDownList selected value


I have a DropDownList that I fill on Page_Load. When I try to get the selected value string id = myDropDownList.SelectedValue.ToString(); Every time I only got the 1st Value, but when I change the value of the DropDownList and check for the string id It always shows my the 1st value.

This is my Page_Load

protected void Page_Load(object sender, EventArgs e)
    {
        if (commesseDataSource.Count != 0)
        {
            initComboCommesse();
        }

        if (Session["Matricola"] != null)
            matricolaDip = Convert.ToInt32(Session["Matricola"]);

        if (Session["LivLogin"] != null)
            livlogin = Convert.ToInt32(Session["Matricola"]);

    }

this Is how I bind the DropDown

private void initComboCommesse()
    {
        myDropDownList.DataTextField = "Value";
        myDropDownList.DataValueField = "Key";
        myDropDownList.DataSource = commesseDataSource;
        myDropDownList.DataBind();
    }

I've already tried to

 protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
 {
      string id = myDropDownList.SelectedValue.ToString(); // I always get the 1st value of the Drop Down
 }

And also

 protected void myDropDownList_TextChanged(object sender, EventArgs e)
 {
      string id = myDropDownList.SelectedValue.ToString(); // I always get the 1st value of the Drop Down
 }

But none of these had worked, I would like to know how to get the selected value of the DropDownList, every time I selected a new value In the DropDownList


Solution

  • Try This:

    When You Insert In your DropDownList Value In Database then you need to change:

    string id = myDropDownList.SelectedItem.Value.ToString();