Loop through a checkbox list
Asked Answered
M

3

6

I am building a checkbox lists:

<asp:CheckBoxList ID="CheckBoxes" DataTextField="Value" DataValueField="Key" runat="server"></asp:CheckBoxList>

And trying to get the value's of the selected items:

List<Guid> things = new List<Guid>();
foreach (ListItem item in this.CheckBoxes.Items)
{
    if (item.Selected)
        things.Add(item.Value);
    }
}

I get the errror

"The best overloaded method match for 'System.Collections.Generic.List.Add(System.Guid)' has some invalid arguments "

Melesa answered 15/7, 2010 at 21:58 Comment(1)
If an item from the list is selected, you want to add this same item to the thing list. Is this what you are trying to do?Manful
M
8

The 'thing' list is excepting a Guid value. You should convert item.value to a Guid value:

List<Guid> things = new List<Guid>();
foreach (ListItem item in this.CheckBoxes.Items)
{
  if (item.Selected)
    things.Add(new Guid(item.Value));
}
Manful answered 15/7, 2010 at 22:5 Comment(0)
C
4

ListItem.Value is of type System.String, and you're trying to add it to a List<Guid>. You could try:

things.Add(Guid.Parse(item.Value));

That will work as long as the string value is parsable to a Guid. If that's not clear, you'll want to be more careful and use Guid.TryParse(item.Value).

Campbellite answered 15/7, 2010 at 22:3 Comment(0)
A
0

If your List's Add method does accept GUID's (see the error message), but isn't accepting "item.value", then I'd guess item.value is not a GUID.

Try this:

...
things.Add(CTYPE(item.value, GUID))
...
Assets answered 15/7, 2010 at 22:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.