Very early in the life of a web form in ASP.NET, you may need to know what control fired the event that caused the post-back to occur.  Perhaps you need to know what button was clicked before the click event handler is executed.  If that scenario is the one you find yourself in, then the following code can help!

If you include the following extension method in your code, you can get the ID of the event causing control from the HttpRequest instance:

public static string GetEventTargetId(this HttpRequest req)
{
    return GetOriginalControlId(req.Form["__EVENTTARGET"]);
}// extension method

The above code is dependent on a helper method to strip the ugly nonsense potentially added while the control was rendered (can now be avoided in ASP.NET 4.0).  The helper method is defined below:

public static string GetOriginalControlId(string renderedControlId)
{
    if (renderedControlId == null) return null;
    int indexOfSeparator = renderedControlId.LastIndexOf('$');
    if (indexOfSeparator >= 0)
    {
        renderedControlId = renderedControlId.Substring(indexOfSeparator + 1);
    }
    return renderedControlId;
}// method

Posted in: code  Tags:
palermo4 posted on October 22, 2009 10:06

For about a year now, I have rewritten all of the introductory courses at Interface Technical Training to use ASP.NET as the front end application.  Other courses (including Microsoft titles) typically start the student in a Console and graduate them to a Windows application.  In my classes, students learn the language in the context of (in my opinion) the most popular technology - ASP.NET.

Instead of Console.WritleLine("Hello World")...
...why not Label1.Text = "Hello World"?

The benefit of this approach is that students are learning a .NET language (C# or Visual Basic) in the context of real-world scenarios.  In the intro classes, this includes how to parse querystrings, how to parse text from textboxes into numeric data for processing, and how to manage and filter lists of data on web page (to name a few).

With Visual Studio 2010 now in Beta 2, I now demonstrate how what they learn also works in the new .NET 4.0 world.


Posted in: commentary  Tags: ,
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010 J. Michael Palermo IV