How to set checkboxes selected in an array in C #

0

Hello, I'm new to developing in C # and I have in my form an option for fruit selection

Grape [] Pear [x] Apple[] Banana [x]

How could I store in an array only the selected checkboxes?

    
asked by anonymous 08.07.2018 / 19:21

1 answer

2

In this case you can use a CheckboxList and navigate through the Options (Items) by checking which one you are selecting. In the example I put 2 of the 4 options marked and I used LINQ to go through all and add in an array only those selected:

HTML

<form id="form1" runat="server">
    <div>
        <asp:CheckBoxList ID="ckbFrutas" runat="server">
            <asp:ListItem Selected="True" Value="1">Uva</asp:ListItem>
            <asp:ListItem Value="2">Pêra</asp:ListItem>
            <asp:ListItem Selected="True" Value="3">Maça</asp:ListItem>
            <asp:ListItem Value="4">Banana</asp:ListItem>
        </asp:CheckBoxList>
    </div>
</form>

C #

protected void Page_Load(object sender, EventArgs e)
{
    //LINQ
    ListItem[] selected2 = ckbFrutas.Items.Cast<ListItem>().Where(li => li.Selected).ToArray();
}

As I do not know which event is doing this, I put it in Page_Load just to demonstrate it. If you prefer to use a normal foreach instead of LINQ and if the CheckboxList options are being populated dynamically (the amount may vary), use a List (List) structure instead of array so you do not have to resize all the time .

Tocapturethevalue,takethe"Value":

//LINQ
List<string> selected2 = ckbFrutas.Items.Cast<ListItem>().Where(li => li.Selected).Select(li => li.Value).ToList();

Or:

foreach (ListItem item in ckbFrutas.Items)
{
    if (item.Selected)
    {
       string selectedValue = item.Value;
    }
}

See that in the case I showed it it will return the values "1" and "3"

    
08.07.2018 / 19:48