views:

980

answers:

2

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?

+3  A: 

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

RichardOD
Ah crap! You got it on the head. My Refresh() method (repopulates most controls) was outside of my !Page.PostBack. <arggghhhh/>Thanks!
Keith Barrows
Don't feel bad- it's an easy mistake to make!
RichardOD
A: 

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.

Kelsey