user147215
user147215

Reputation:

Loop through a checkbox list

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 "

Upvotes: 6

Views: 21055

Answers (3)

dave
dave

Reputation: 1364

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))
...

Upvotes: 0

jdecuyper
jdecuyper

Reputation: 3963

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));
}

Upvotes: 8

Samuel Meacham
Samuel Meacham

Reputation: 10425

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).

Upvotes: 4

Related Questions