A fun with CheckBoxList, Lambda Expression and SelectedItem

Friend of mine wanted to select the items of CheckBoxList based on the value from a Enum List. Then I thought I should try. This article is about that. So what I did I created a simple website with a default page and CheckBoxList in the page. On the page load event the list will be populated based on the value in the List.

The code I wrote is as below,

Default.aspx page

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:CheckBoxList ID="cboList" runat="server">
        <asp:ListItem Text="One" Value="One"></asp:ListItem>
        <asp:ListItem Text="Two" Value="Two"></asp:ListItem>
        <asp:ListItem Text="Three" Value="Three"></asp:ListItem>

and the code behind for the Default.aspx is as below,

namespace WebApplication2
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    public partial class _Default : Page
        public enum MyEnum
        protected override void OnLoad(EventArgs e)
            IList<MyEnum> myEnums = new List<MyEnum>();
        private void UsingQueryExpression(IList<MyEnum> myEnums)
            var temp = (from listItem in cboList.Items.Cast<ListItem>()
                       join myEnum in myEnums on listItem.Value equals myEnum.ToString()
                       select (listItem.Selected = true)).ToList();
        private void UsingGenericLambdaExpression(IList<MyEnum> myEnums)
            var temp = cboList.Items.Cast<ListItem>()
                listItem => listItem.Value,
                myEnum => myEnum.ToString(),
                ((listItem, myEnum) => listItem.Selected = true)
        private void UsingLambdaExpression(IList<MyEnum> myEnums)
            var temp = cboList.Items.Cast<ListItem>()
                listItem => listItem.Value,
                myEnum => myEnum.ToString(),
                ((myEnum, listItem) => myEnum))
                .Select(selectedListItem => selectedListItem.Selected = true).ToList();

happy to learn from others.


No comments:

Post a Comment