How To: Get the Value of a Control Without an instance of the Control

On my quest to write one blog a day in July, here is my first post regarding how to get the value of a control without the control instance.  This can be very helpful for HTTP pipeline development or when the value of the control is needed very early in the page lifecycle.

public static string GetControlValueFromRequest(string controlId)
{            
    string requestValue = null;
    controlId = controlId.ToLower();
    HttpRequest req = HttpContext.Current.Request;
    string eventTarget = req.Form["__EVENTTARGET"] ?? string.Empty;
    if (eventTarget.ToLower().EndsWith(controlId))
    {
        requestValue = req.Form["__EVENTARGUMENT"];                
    }
    if (string.IsNullOrEmpty(requestValue))
    {
        foreach (string id in req.Form.AllKeys)
        {
            if (id.ToLower().EndsWith(controlId))
            {
                requestValue = req[id];
            }
        }
    }            
    return requestValue;
}
del.icio.us Tags: , , , ,

6 Comments

  • If there are two controls named 'mail' and 'email' if you are searching using

    .EndsWith( controlId )

    you could introduce the wrong value. Wouldn't something like (not tested)

    .EndsWith( this.Page.IdSeparator + controlId )

    be better? The idea would be to try to prevent as many false positives as possible...

  • That's really interesting, but where can I found more information on how this works "behind the scenes?"

  • Now that is cool, but this line:

    string eventTarget = req.Form["__EVENTTARGET"] ?? string.Empty;

    is even cooler...how have I ever missed ??, so useful.

    Thanks

  • David,

    I agree. I made some changes to the method, and I will post it to the blog soon! Thanks for your insight!

  • Gareth,

    I agree, it took me a year after 2.0 came out before I discovered that one!

  • All, I have a form (FRM_ShowAll) on which I have placed a number of instances of the same sub-form (FRM_Assign) as different child forms.

Comments have been disabled for this content.