Wednesday, November 21, 2007

Getting Information From input Tags On A Page In .NET Using Request.Form.AllKeys & Request.Form.Get

While creating a web-based software program recently I came across a small problem. This program dynamically creates a number of textboxes inside of rows that reside inside of a table server control. The rows along with the cells & textboxes are all dynamically created based on user input. Once the textboxes have been created, the user is able to enter information into them. Then the software has to read that information and process it.

This sounds like a simple process right? Well it is a simple process, however, I ran into one problem. When you dynamically create text boxes they are rendered as input tags in the html and not as .net server controls with this tag . This creates an issue when you need to loop through the controls and get the information from the textboxes.

Now you may be thinking, what is she talking about? I can just loop through the Table’s row collection and get a reference to the textbox controls that way. Well I’m here to tell you that won’t work. Sorry L. You may be thinking that you can get to the textboxes via the form’s control collection. Well I’m here to tell you that won’t work either. So what’s a girl, or a guy, to do? Well ladies and gentleman, the answer is really simple.

All you have to do is use Request.Form.AllKeys and Request.Form.Get and you will be able to get a reference to those pesky controls all day long. Here is code you can use. In my case, I named those textboxes with a generic name and just incremented the numbers. So if a user requested 120 boxes, my textbox names would range from uTxt1 to uTxt120. That way I could loop through and use StartsWith(“uTxt”). Here is my code:

int i = 0;
string sValue = "";

foreach (string s in Request.Form.AllKeys)
//this lets me know that I have reached one of the controls that
//I dynamically created earlier
if (s.StartsWith("uTxt"))
sValue = Request.Form.Get(i);


That’s it! Now you can reference any of the controls at any time without any issues.
By the way, if you are using placeholder controls , Request.Form.AllKeys and Request.Form.Get really come in handy since placeholders render the asp server controls used for input as input controls and not server controls.



Server controls are being rendered as html input controls in the final page and you need to access the values of these controls in the code-behind at runtime.

You can't get a reference by looping the control collections of the aspx page because all of the values return null and the controls values you need are being held by html controls and not server controls.

Use Request.Form.AllKeys in combination with Request.Form.Get to get to the particular control and value you need. You can loop through the AllKeys collection using a foreach loop and then reference the item you need using Get.

No comments: