How to arm selected checkbox in an array in c#

Asked

Viewed 158 times

0

Hello, I’m new in development in c# and have in my form an option for fruit selection

Grape[] Pera[x] Apple[] Banana[x]

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

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 marked options and used LINQ to go through all and add in an array only the selected ones:

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 put in Page_load even just to demonstrate. If you prefer to use a normal foreach instead of LINQ and if the Checkboxlist options are being filled dynamically (the amount may vary), use a list(List) structure instead of an array so you don’t have to resize all the time.

inserir a descrição da imagem aqui

To capture the value take the "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 will return the values "1" and "3"

  • rodrigorf thanks for the reply! I did here and gave it right! How would I send only the value of that list and put it inside a string variable? I’m using Entity to register in an SQL database and I already have everything working. I just needed to send the value of the checks selected. Whenever I try to register it appears as System.Collections.Generic.List`1[System.String].

  • @Danielpelissari beauty, I edited the answer with two examples of how to capture the value of the item instead of the whole object. The second example does not store in list, it is only to show that you can use foreach and do what you want with the selectedValue variable

  • great @rodrigorf, thank you so much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.