views:

168

answers:

2

I have a simple ASP.NET web form as below:

<form id="form1" runat="server">
    <asp:TextBox ID="txt" runat="server"></asp:TextBox>
    <asp:DropDownList ID="ddl" runat="server">
        <asp:ListItem Text="X" Value="X"></asp:ListItem>
        <asp:ListItem Text="Y" Value="Y"></asp:ListItem>
        <asp:ListItem Text="Z" Value="Z"></asp:ListItem>
    </asp:DropDownList>
    <asp:Button ID="btn" runat="server" Text="Button" />
</form>

Request.Form contains the following key/value pairs:

[0] _VIEWSTATE
[1] _EVENTVALIDATION
[2] txt
[3] ddl
[4] btn

How do I differentiate the button (btn) from Textbox value (txt) or DropDown List value (ddl)? Or do I need to somehow come up with a naming convention? I am trying to iterate Request.Form object and save form values into a hashtable for later use.

Thanks.

+1  A: 

You can't. To the server it's a simple name:value collection.

Why not let the framework take care of this for you?

In the codebehind you can retrieve the values via their properties:

ddl.SelectedText
txt.Text
Chuck Conway
So custom naming convention is the way to go?
Jeffrey C
You can, but that would be reinventing the wheel. ASP.Net already does this.
Chuck Conway
Becuase the html controls are sort of dynamically rendered so I only want to collection the posted values and save into a hashtable. If you do txt.Text, ASP.NET just does a look up like Request.Form["txt"] to get the value I believe.
Jeffrey C
+2  A: 

The way to differentiate between the various Request.Form fields is to associate the field names with the control names--which is exactly what each control does.

Each control knows its own ID. During the Initialization phase, each control sets or restores its state based on both Request.Form and ViewState.

For dynamically created controls, the Framework will handle this for you, provided that you create the controls and add them to the control tree before the Init phase (such as in the OnPreInit event handler).

If you want to do it yourself, you can mimic the process by walking the control tree.

RickNZ