Loop through a checkbox list

放肆的年华 提交于 2019-12-08 20:02:05

问题


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 "


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/3260428/loop-through-a-checkbox-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!