1

I have a array of checkboxes, 33 in total. Because the checkboxes are all over the page, it needs to be in an array (right?).

The code-behind looks like this:

CheckBox[] variableName = new CheckBox[33];

        variableName[0] = idCheckBox1;
        variableName[1] = idCheckBox1;
        variableName[2] = idCheckBox1;
        variableName[3] = idCheckBox1;

and so on...

ASP.NET:

<asp:CheckBox ID="idCheckBox1" runat="server" Value="1" />
<asp:CheckBox ID="idCheckBox2" runat="server" Value="2" />
...

The checkboxes are totally optional. Now how do i get the value of the checked boxes only in a variable?

1 Answer 1

2

It does NOT need to be an array.
This is how you get all the CHECKED checkboxes in your form from the CodeBehind:

var names = formCollection.AllKeys.Where(c => 
                    c.StartsWith("idCheckBox") && 
                    formCollection.GetValue(c) != null &&
                    formCollection.GetValue(c).AttemptedValue == "1");
Sign up to request clarification or add additional context in comments.

4 Comments

Also, maybe you could benefit from the CheckBoxList Class: msdn.microsoft.com/en-us/library/…
Where did you get 'formCollection' from? If i use my form1, there is no AllKeys.
Alright, in my case 'form1' then... But when i use it like this: var names = form1.AllKeys.Where(c => c.StartsWith("idCheckBox") && form1.GetValue(c) != null && form1.GetValue(c).AttemptedValue == "1"); the AllKey isn't recognized. I'm using System.Collections...
The Linq namespace was already imported :) Well, when i use 'Request.Form.AllKeys', AllKeys is recognized. Strange... (sorry, not a big c# expert ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.