Brian Green
Brian Green

Reputation: 567

Why is my drop down list only selecting the first item in the list?

I'm making an e-commerce site for a friend and I'm looking to make it as scalable as possible. I'm assuming at some point their community will grow to overwhelming numbers and they will eventually need to appoint new admins. I don't want them coming to me to configure the WSAT. I've put in two drop down lists and a button. One pulls the users and concatenates the user name with the role they are in. The second pulls all the roles. The button removes the selected user from whatever they are in and puts them in the role that is selected in the drop down list.

    <asp:DropDownList ID="ddlUsers" runat="server" AppendDataBoundItems="True" 
    DataSourceID="dsMembers" DataTextField="Info" DataValueField="Username">
    <asp:ListItem>--Select a User --</asp:ListItem>
    </asp:DropDownList>
    &nbsp;
    <asp:DropDownList ID="ddlRoles" runat="server" AppendDataBoundItems="True" 
    DataSourceID="dsRoles" DataTextField="RoleName" DataValueField="RoleId" 
    style="margin-bottom: 0px">
    <asp:ListItem>--Select Privilege--</asp:ListItem>
    </asp:DropDownList>
    &nbsp;<asp:LinkButton ID="lbtnChangeRole" runat="server" 
    onclick="lbtnChangeRole_Click">Change Role</asp:LinkButton>

However, every time I click the button it just automatically selects the first user in the list no matter which one I've selected.

This is the code behind.

protected void lbtnChangeRole_Click(object sender, EventArgs e)
{
    string user = ddlUsers.SelectedValue.ToString();
    string role = ddlRoles.SelectedItem.ToString();

    string currentRole = Roles.GetRolesForUser(user)[0];
    //check to see if the user is already in role

    if (!Roles.IsUserInRole(user, role))
    {
        Roles.AddUserToRole(user, role);
        Roles.RemoveUserFromRole(user, currentRole);

    }
}

Upvotes: 2

Views: 5749

Answers (1)

David
David

Reputation: 218837

Are you populating the lists in Page_Load? A common cause for this symptom is that the lists are being re-populated on post back and, thus, defaulting to the first item. This is generally avoided by wrapping the list-populating code in a check for the post back:

if (!IsPostBack)
{
    // populate the drop down lists, and anything else for loading the page.
}

Note that, when a post back occurs, Page_Load is called before the click event handler is called.

Upvotes: 5

Related Questions