Check multiple items in ASP.NET CheckboxList
Asked Answered
S

4

9

I try to check multiple values in ASP.NET CheckboxList but I couldn't.
I Wrote :

chkApplications.SelectedValue = 2;
chkApplications.SelectedValue = 6;

But it just selects item with value '6'
What's wrong ?

Sisterly answered 10/7, 2011 at 10:49 Comment(0)
M
22

The best technique that will work for you is the following:

chkApplications.Items.FindByValue("2").Selected = true;
chkApplications.Items.FindByValue("6").Selected = true;

OR you can simply do it like...

  foreach (ListItem item in chkApplications.Items)
    {
        if (item.Value == "2" || item.Value == "6")
        {
            item.Selected = true;
        }
    }
Montreal answered 10/7, 2011 at 10:57 Comment(1)
That will throw exception if value is not found. Also needs to iterate the complete collection once for every call to FindByValue.Alcantar
A
5
foreach (var item in cb.Items.Cast<ListItem>()
        .Where (li => li.Value == "2" || li.Value == "6"))
   item.Selected = true;
Alcantar answered 10/7, 2011 at 10:53 Comment(0)
S
5

you can put the value in a list (MyList), and use FindByValue to check them.

foreach (var item in MyList)
{
    checkBoxList.Items.FindByValue(item.id).Selected = true;
}
Sosanna answered 8/9, 2012 at 9:3 Comment(0)
S
-1

Instead of trying to select the item through chkApplications.SelectedValue try chkApplications.Items.Item(2).Selected = True chkApplications.Items.Item(6).Selected = True

Spiker answered 10/7, 2011 at 11:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.