1

I am receiving long string of checked html checkbox values (Request.Form["mylist"] return Value1,Value2,Value3....) on the form post in ASP.NET 2.0 page.

Now I simply want to loop these but I don't know what is the best practice to loop this array of string. I am trying to do something like this:

foreach (string Item in Request.Form["mylist"]){
  Response.Write(Request.Form["mylist"][Item] + "<hr>");
}

But it does not work.

3 Answers 3

7

You have to split the comma separated string. Try

string myList = Request.Form["myList"];
if(string.isNullOrEmpty(myList))
{
    Response.Write("Nothing selected.");
    return;
}
foreach (string Item in myList.split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries))
{
  Response.Write(item + "<hr>");
}
Sign up to request clarification or add additional context in comments.

Comments

0

I recommend to do not use Split in Form values to prevent splitting values with commas.

string myList = Request.Form.GetValues("myList");
foreach (var Item in myList)
{
  Response.Write(item + "<hr>");
}

Comments

0

To complete and debug DolceVita's answer, which has an important and correct point...

Given the following example HTML

<p>Select numbers for a sum:</p>
<input type="checkbox" id="c1" name="myList" value="1"/><label for="c1">1</label>
<input type="checkbox" id="c2" name="myList" value="2"/><label for="c2">2</label>
<input type="checkbox" id="c3" name="myList" value="3"/><label for="c3">3</label>

you can read selected checkboxes by

var sum = 0;
var selectedNumbers = Request.Form.GetValues("myList");

if (selectedNumbers != null)
{
    foreach (var selectedNumber in selectedNumbers)
    {
        // my example uses integers
        var number = int.Parse(selectedNumber);
        sum += number;
    }
}

Response.Write("<p>Sum: " + sum + "</p>");

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.