Using C # to iterate form fields with the same name

I have a section of the form that I need to handle differently than the rest of the form results. In the section requiring special processing, I need to iterate over 3 fields of the form with the same name. They must have the same name, I can’t change it. The section of the form that I am referencing looks something like this:

<td><input name="Color" size="20" value="" type="text"></td> <td><input name="Color" size="20" value="" type="text"></td> <td><input name="Color" size="20" value="" type="text"></td> 

With C #, I try something like this:

I am trying to handle this as follows:

 int i; for (i = 1; i <= Request.Form["Color"][i]; i++) { colorName.Text += Request.Form["Color"]; } 

This results in the following exception:

System.NullReferenceException: Object reference not set to an instance of an object.

How do I handle form fields with the same name?

+6
c # forms webforms request
source share
4 answers

You do not need to do any splits or other special magic; you can just get an array of strings from ASP.NET:

string [] values ​​= Request.Form.GetValues ​​("Color");

+11
source share

I would suggest adding each form to the list and using the ForEach statement instead, although it is slightly longer than what you are already trying to do.

eg.

 private List<Request.Form> newList = new List<Request.Form>(); newList.Add(FormName1); newList.Add(FormName2); newList.Add(FormName3); foreach(Request.Form form in newList) { //perform logic } 

Note. I assume Request.Form is the class name for the Form itself.

I have not tested this myself, so there may be several errors in it, I hope this helps anyway.

0
source share

It is important to remember that published form values ​​are nothing more than collecting name / value data, where the value is a simple string. Therefore, it does not make sense to have several form fields with the same name. I don’t even know if this is really allowed.

But, as you say, you cannot change that. I checked the quick check in IE and Chrome and, at least in these browsers, it seems that they send multiple form fields with the same name as the comma-separated string. You might want to check something else to make sure that this behavior is consistent across browsers.

Given this, you could say:

 string colorValues = Request.Form["Color"]; string [] colors = colorValues.Split(','); 

Each element in the color array now corresponds to the value of each input element that was sent.

0
source share

Either Request.Form ["Color"] is null, or colorName is not displayed on the aspx page. I can not say based on your code. Otherwise, it looks right. What type of html element is Color? If this is just an html element, make sure that it has both id and name attributes.

-one
source share

All Articles