Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lambda expression with asp.net DataList in C#

Tags:

c#

asp.net

lambda

I have created a DataList on aspx file that contains checkbox control that repeated base on a data pulled from database.

I want to get DataList items and work on it, I already did use foreach loop, but I want to select and filter the items using lambda.

I couldn't convert the DataList.items to List nor an Array. there is DataList.items.CopyTo but it copies to Array object and couldn't convert to DataListItem [] array.

this is what has been done:

int count = 0;

foreach (DataListItem item in weaknesses.Items)
{
    CheckBox weakness = (CheckBox)item.FindControl("cbWeakness");
    if (weakness.Checked)
    {
        count++;
    }
}

and this is what I'm trying to do:

count = weaknesses.Items.Where(i => ((CheckBox)i.FindControl("cbWeakness")).checked).Count();
like image 218
Ahmed Abd Elmoniem Avatar asked Dec 07 '25 20:12

Ahmed Abd Elmoniem


1 Answers

You can do that with this lambda.

int count = DataList1.Items.Cast<DataListItem>().Where(x => ((CheckBox)x.FindControl("CheckBox1")).Checked).Count();

The DataList

<asp:DataList ID="DataList1" runat="server">
    <ItemTemplate>
        <asp:CheckBox ID="CheckBox1" runat="server" />
    </ItemTemplate>
</asp:DataList>
like image 191
VDWWD Avatar answered Dec 09 '25 08:12

VDWWD