Loop through a checkbox list

user147215 picture user147215 · Jul 15, 2010 · Viewed 19.6k times · Source

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 "

Answer

jdecuyper picture jdecuyper · Jul 16, 2010

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