Dropdown only returns the text / value of the element from the first element

EDIT: So I found that this line was listItem.Value = rdr["lvl"].ToString();

adding the same value for every item in the dropdown. Since every text element had the same value, I believe it was always the default for the first text element. Now I am lvl

passing through another request instead of the dropdown. Thanks for the helpful input!

I am trying to accomplish a fairly simple task that I have done many times before. For some reason, I cannot get my dropdown to pass SelectedItem

and correctly SelectedValue

.

SelectedItem

and SelectedValue

always return for the first item in the dropdown, no matter which item I select.

What am I doing wrong?

Dropdown and Button Definition:

<asp:DropDownList ID="DropDownList1" runat="server" >
</asp:DropDownList>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

      

Increasing the dropdown list on the PageLoad page:

myConnection.Open();
SqlCommand rpt = new SqlCommand(getreports, myConnection);
SqlDataReader rdr = rpt.ExecuteReader();
if (!Page.IsPostBack)
{
    while (rdr.Read())
    {
        ListItem listItem = new ListItem();
        listItem.Text = rdr["manager"].ToString();
        listItem.Value = rdr["lvl"].ToString();
        DropDownList1.Items.Add(listItem);
    }
    rdr.Close();
    myConnection.Close();
}

      

Code for clicking the button, which should go through SelectedItem

and SelectedValue

:

    protected void Button1_Click(object sender, EventArgs e)
    {            
        string user = DropDownList1.SelectedItem.Text;
        string lvl = DropDownList1.SelectedValue;
        Label1.Text = user;
        Label2.Text = lvl;
    }

      

+3


source to share


1 answer


I realized that the same value was assigned to each item. It was for this reason that the first item in the dropdown kept going through regardless of the selection. As long as the values ​​are different, all of the above codes work as expected.



0


source







All Articles