Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP:ListBox - no selected items on postback?

I have the following markup:

<tr>
    <td valign="top" align="left">
        <asp:Label ID="Label1" runat="server" Text="Available Roles" />
        <br />
        <asp:ListBox ID="availableRolesListBox" runat="server" SelectionMode="Multiple" Width="100px" Rows="10" AutoPostBack="false" />
    </td>
    <td valign="top" align="center">
        &nbsp;
        <br />
        <asp:Button ID="addToRole" runat="server" Text="--->" OnClick="addToRole_Click" />
        <br />
        <asp:Button ID="removeFromRole" runat="server" Text="<---" OnClick="removeFromRole_Click" />
    </td>
    <td valign="top" align="left">
        <asp:Label ID="Label2" runat="server" Text="User In Roles" />
        <br />
        <asp:ListBox ID="userInRolesListBox" runat="server" SelectionMode="Multiple" Width="100px" Rows="10" AutoPostBack="false" />
    </td>
</tr>

And the following in code-behind:

protected void addToRole_Click(object sender, EventArgs e)
{
    // Add user to the selected role...
    foreach (ListItem myItem in availableRolesListBox.Items)
    {
        if (myItem.Selected)
        {
            Roles.AddUserToRole(userListBox.SelectedItem.Value, myItem.Text);
        }
    }

    Refresh();
}

When I step into the code-behind absolutely no items are selected! What am I forgetting?

like image 343
Keith Barrows Avatar asked Oct 15 '25 20:10

Keith Barrows


2 Answers

Are you perhaps rebinding the availableRolesListBox each time, instead of if(!IsPostback)?

like image 98
RichardOD Avatar answered Oct 17 '25 10:10

RichardOD


You could check a few things.

CHeck that you are NOT reloading the listbox after each postback. Also, you might want to make sure you do not have ViewStateEnabled="false" for a parent container.

Other than that your code looks like it should be ok, debugging any further would require more code or information.

like image 36
Kelsey Avatar answered Oct 17 '25 11:10

Kelsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!