November 04, 2010
This is a class that add an extension to the CheckBoxList class to return a comma separated string with all the selected values.You call this function by the following:
string mySelectedValues = myCheckBoxList.GetSelectedValues();
The class to place somewhere in you project (remember to add a using-reference to any class you want to call this function from:public static class CheckBoxListExtension {
public static string GetSelectedValues(this CheckBoxList checkBoxList) {
string retval = string.Empty;
try {
foreach (ListItem item in checkBoxList.Items) {
if (item.Selected) {
retval += item.Value + ',';
}
}
retval.TrimEnd(',');
}
catch (Exception) {
}
return retval;
}
}
Or the same code if LINQ is your poison:
public static class CheckBoxListExtension {
public static string GetSelectedValues(this CheckBoxList checkBoxList) {
string retval = string.Empty;
try {
retval = checkBoxList.Items.Cast<ListItem>().Where(item => item.Selected).Aggregate(retval, (current, item) => current + (item.Value + ','));
retval.TrimEnd(',');
}
catch (Exception) {
}
return retval;
}
}
Comments
comments powered by Disqus