Jul
23
2010
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