Main FAQ Category: WebForms (12)
Also in: Beginner (39) 
How to Iterate through all submitted values in the HTML Form on ASP.NET page?
Posted: 25-Apr-2008
Updated: 25-Apr-2008
Views: 16199

If you were developing some code in PHP language surely you remember how easy is to access the values of submitted HTML Form via $_POST and $_GET global arrays.

Off course, ASP.NET also has the similar functionality, even more, because of its Strongly Typed approach..

Every ASP.NET Page has public property Request that is an instance of HttpRequest class and represents the current HTTP Request.
This class has public property Form that is an instance of NameValueCollection class that holds all the submitted HTML Form variables.
(This includes hidden input fields that ASP.NET creates behind the scenes and ViewState as well...)

Actual names of the submitted variables are in AllKeys string array property, and every key can be used to access the value in the collection via the default indexer Item property.

TIP: Since Item property is a default indexer for the collection, we can omit its name when retrieving the collection values and just use the name of the collection. See more on indexers on the MSDN Using Indexers page.

Here is the code that you can use in your Page_Load event handler to display all the submitted HTML Form variables names and values:

protected void Page_Load(object sender, EventArgs e)

{

    if (Page.IsPostBack)

    {

        NameValueCollection submittedValuesCollection = Request.Form;

 

        Response.Write("<b>Submitted Values:<br /></b>");

        foreach (string key in submittedValuesCollection.AllKeys)

        {

            Response.Write (string.Format("{0} => {1}<br />", key, submittedValuesCollection[key]));

        }

        Response.Write("<br /><br />");

    }

}