[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( typeofstring ) );
}

Posted so:

  1. I can find it later
  2. I can maybe save the next guy some time
  3. The piranha haters community can point out how this could be done better.

22 Comments

  • Jon,

    Sorry, I fail to see the difference in your method and the MSDN method. You are also iterating through the collection and seeing if each is checked.



    void Check_Clicked(Object sender, EventArgs e)

    {

    Message.Text = &quot;Selected Item(s):&lt;br&gt;&lt;br&gt;&quot;;\

    // Iterate through the Items collection of the CheckBoxList

    // control and display the selected items.

    for (int i=0; i&lt;checkboxlist1.Items.Count; i++)

    {

    if (checkboxlist1.Items[i].Selected)

    {

    Message.Text += checkboxlist1.Items[i].Text + &quot;&lt;br&gt;&quot;;

    }

    }

    }

  • True. What I meant is that I don't think it makes sense to manually iterate the checkboxlist items every time. The utility function does it internally, so it's no faster, but I'm not writing the same stupid code over and over.

  • So you, er, refactorinated it.



    Well, as a friend of mine used to say, &quot;they can't all be pearls.&quot;

  • Yessir. See my reasons for posting at the bottom of the post.

  • as a piranha:

    the parameter could be of type ListControl which would allow the function to be reusable for other type of controls (checkboxlist, listbox).



    and a foreach instead of a for?





  • It's funny when confronted with a piece of sample code how a load of geeks usually all go:



    - Yeah so?

    - It's in the docs.

    - Why not do it like this or that?

    - And in some scenarios: I can do it better, here's how, blah blah.



    It's just so bloody typical.



    I know exactly what you're trying to do John, for your obvious reasons at the bottom of the post. Just a shame people can't take your post it for what it is: a simple helper function. Not effing rocket science!



    Cheers,

    Wim

  • Wim:

    If that's at all directed @ me, it isn't fair. He specifically posted it so that it could be improved upon by the community. Sure that might have been said in jist, knowing that it would happen one way or another, but why not if the comment is helpful to others as well?

  • Oh and if it's a Utility function, better mark it static?



    Sorry!!!

  • Karl,



    Not typically, as you can see, we're all guilty as charged, me included.



    Sometimes I just hate it though. It's geeks genes I guess.



    We always have to butt in here there and everywhere and know better.



    Wim

  • I don't know if this is just my personal preference or good OOP, but I like to make helper methods like these members of the class they are manipulating rather than static, or otherwise, members of another class. It's easier to do that in a language that allows for mixins/prototypes. I have't studied it much yet, but I think C# 2.0 allows you to add members to a class w/o having to derive from the class. Anonymous methods? But yeah, there aren't a whole lot of other ways to determine which items are selected in that kind of list.

  • You said &quot;The MSDN solution is ugly&quot; which lead me to believe &quot;your method&quot; was better which lead to posting number 1



    It all makes sense now.

  • Thanks all for the recommendations. That's why I posted it. I think a simple static function operating on a listcontrol makes sense to me for a single function.



    Ron -

    Yeah, agree. But part of what I thought was ugly about the MSDN solution is that it requires you to manually loop through the items every time. More code -&gt; more bugs -&gt; less time for content-rich posts -&gt; this post -&gt; these comments. I'm trying to break the cycle.

  • Hey, thanks for posting this! You saved me a good couple of hours of tedious cut/paste.



    Not being a hater or a piranha, I'll just give you a pass on #2 (I can maybe save the next &lt;b&gt;guy&lt;/b&gt; some time) ...

  • Sorry, Heather! Glad I saved you a little time, though.

  • is it utility function constructor or destructor but i caN'T UNDERSTAND

  • Syed - It's just a simple utility function. You can add it to a page, a utility class, etc. Then you can call it from an ASPX page:

    string[] selections = CheckboxListSelections(CheckBoxList1);

  • The function does not return values
    it return System.String[]

  • Yasser,
    System.String[] is the collection of values. Each item in the list has a string value, therefore an array of strings *is* the collection of selected values.

    Jon,
    I've done the same thing many times myself and see what you're saying. I read your comment as "there should be a method on ListControl called SelectedValues that returns the complete collection of selected values for that control". The utility class is an acceptable substitute, although it always grates with me to have yet another static utility class.

  • Dim listItemObj As ListItem

    For Each listItemObj In tempCheckBoxList.Items
    If listItemObj.Selected = True Then
    'a lot of stuff can happen here
    End If
    Next

  • Thanks Jon, this came in handy for a late sunday night start of a long work week :)

  • Dim ret As String = ""
    For Each i As ListItem In Ck_tags.Items
    ret += IIf(i.Selected = True, i.Value.ToString + ",", "")
    Next

  • hi,
    this is a solution using Linq and lambda

    return list.Items
    .Cast()
    .Where(item => item.Selected)
    .Select(item => item.Value)
    .Cast()
    .ToArray();

Comments have been disabled for this content.