3
votes

EDIT: So I found that this line listItem.Value = rdr["lvl"].ToString(); was adding the same value for each item in the dropdown. Since each text item had the same value, I guess it always defaulted to the first text item. I'm now passing lvl through another query instead of the dropdown. Thanks for all the helpful input!

I'm trying to accomplish a pretty simple task which I've done numerous times before. For some reason, I can't get my dropdown to correctly pass the SelectedItem and SelectedValue.

The SelectedItem and SelectedValue are always returned for the first item in the dropdown, regardless of which item I select.

What am I doing wrong?

Defining dropdown and button:

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

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

Populating dropdown on PageLoad:

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 button click that should pass 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;
    }
1
Where is the code that populates the dropdown being called?Camilo
The dropdown gets populated on PageLoad66Mhz
@Camilo He did wrap it in if (!Page.IsPostPack). I thought of that myself, but unless he's got another location that's doing it on PostBack that's not the issue.ahwm
@ahwm Nope, that's the only place it's being populated66Mhz
The change may not be reaching the backend... Not sure if this will help but have you tried setting AutoPostBack="true" on the DropDownList?Evan Frisch

1 Answers

0
votes

I realized the same value was being assigned for each item. This was the reason the first item in the dropdown kept being passed regardless of the selection. As long as the values are different, all the above code works as expected.