ASP: ListBox - no highlighted items for 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 in the code:

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 enter the code, absolutely nothing is selected! What am I forgetting?

+3
source share
2 answers

Perhaps you bind each time availableRolesListBox, and not if (! IsPostback)?

+7
source

You can check out a few things.

Check that you are NOT reloading the list after each postback. In addition, you might want to make sure that the parent container does not exist ViewStateEnabled="false".

In addition, your code looks as if it should be in order, debugging in the future will require more code or information.

+1

Source: https://habr.com/ru/post/1714789/


All Articles