Helios Rex

Helios Rex

  • NA
  • 3
  • 0

ASP.NET - How to loop through items in a CheckBoxList using LINQ and C#

Sep 19 2008 1:42 PM

Hello guys,

This is probably one of the simplest of questions that anyone can ask. Most of you can probably answer this in your sleep :)

I am absolutely new to ASP.NET and I am trying to get my feet wet by parcticing simple excercises using version 3.5 (both VB and C#).

I am trying to accomplish a simple logic to do the following. I have created a CheckBoxList with 3 items

Apple
Orange
Banana
Peach

The code from my test.aspx looks as follows...

<asp:CheckBoxList ID="cblFruits" runat="server">
 <asp:ListItem Value="1">Apple</asp:ListItem>
        <asp:ListItem Value="2">Orange</asp:ListItem>
        <asp:ListItem Value="3">Banana</asp:ListItem>
        <asp:ListItem Value="4">Peach</asp:ListItem>
</asp:CheckBoxList>

I also have a Submit button as well as a label to display the result as follows...

<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
<br />

<asp:Label ID="lblResult" runat="server" Height="80px" Width="500px"></asp:Label>
<br />

If the user checks Apple and Banana and clicks on the submit button, I want to display something like below...

In the Check Box List you selected Apple with value 1
In the Check Box List you selected Banana with value 3

I used the following c# code in btnSubmit_Click to accomplish it and it works fine.

//Loop through the Check Box list and for each selected item, display its name with appropriate message

foreach (ListItem item in cblFruits.Items)
{
 if (item.Selected == true)
 lblResult.Text += "In the Check Box List you selected " + item.Text + " with value " + item.Value + "<br />";
}

Now I want to accomplish the same using LINQ. I was able to do it in VB with the following code...


        Dim selectionResults = From member In cblFruits.Items _
                      Where member.Selected = True _
                      Select member

        For Each item As ListItem In selectionResults
            lblResult.Text &= "In Check Box List you selected " & item.Text & _
                              " with value " & item.Value & "<br />"
        Next


How can I translate the above snippet of code (that uses LINQ to traverse through the CheckBoxList items) in C#? Your help is grately appreciated.

Thanks in advance
Helios


Answers (2)