Pindub_Amateur
Pindub_Amateur

Reputation: 328

item.Selected is false when the checkboxlist is disabled.

I have a checkboxlist where certain items are disabled for certain users.

enter image description here

When I click on 'Save', the below code is executed.

 foreach (ListItem item in myCheckBoxList.Items)
 {
    if (!item.Selected)
            {
                continue;
            }
    selectedValues.Add(item.Value);
  }  

However, item.Selected evaluates to false for the disabled items even though they're selected.

Is there a way to get around this?

Upvotes: 0

Views: 916

Answers (2)

VDWWD
VDWWD

Reputation: 35514

If the ListItems of the CheckBoxList are added with aspnet, either in code behind or the .aspx page, ViewState will ensure that it will see those disabled checkboxes as checked, even if they are not send to the server.

    protected void Button1_Click(object sender, EventArgs e)
    {
        List<string> selectedValues = new List<string>();
        Label1.Text = "";
        foreach (ListItem item in myCheckBoxList.Items)
        {
            if (item.Selected)
            {
                selectedValues.Add(item.Value);
                Label1.Text += item.Value + "<br>";
            }
        }
    }

And to make the example complete:

    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <br /><br />
    <asp:CheckBoxList ID="myCheckBoxList" runat="server">
        <asp:ListItem Text="Blueberry" Value="Blueberry"></asp:ListItem>
        <asp:ListItem Text="Raspberry" Value="Raspberry"></asp:ListItem>
        <asp:ListItem Text="Blackberry" Value="Blackberry"></asp:ListItem>
        <asp:ListItem Text="Strawberry" Value="Strawberry" Enabled="false" Selected="True"></asp:ListItem>
        <asp:ListItem Text="Gooseberry" Value="Gooseberry" Enabled="false" Selected="True"></asp:ListItem>
    </asp:CheckBoxList>
    <br /><br />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

Upvotes: 1

Imad
Imad

Reputation: 7490

Disabled inputs are never posted to the server, hence it will be set to default value, i.e. false. You can use HiddenField and associate that with each checkbox and set it's value based on it's selection.

Upvotes: 3

Related Questions