[asp.net] Simple utility function to return all selected values from a CheckBoxList
The ASP.NET CheckBoxList.SelectedValue property only returns first item selected. The MSDN solution is ugly - iterate the CBL items checking each one to see if it's selected.
Five minutes of Google-Fu didn't turn up anything, so here's a simple utility function to get a string array of selected values.
public string[] CheckboxListSelections(System.Web.UI.WebControls.CheckBoxList list)
{
ArrayList values = new ArrayList();
for(int counter = 0; counter < list.Items.Count; counter++)
{
if(list.Items[counter].Selected)
{
values.Add(list.Items[counter].Value);
}
}
return (String[]) values.ToArray( typeof( string ) );
}
{
ArrayList values = new ArrayList();
for(int counter = 0; counter < list.Items.Count; counter++)
{
if(list.Items[counter].Selected)
{
values.Add(list.Items[counter].Value);
}
}
return (String[]) values.ToArray( typeof( string ) );
}
Posted so:
- I can find it later
- I can maybe save the next guy some time
- The
piranhahaterscommunity can point out how this could be done better.