Find Control that Caused a Postback
Sometimes there is the need to find the control that caused the postback from outside the event handler. The following code gives you just that:
public static class PageExtensions
{
public static Control FindFiredControl(this Page page)
{
Control control = page;
Boolean asyncPost = (page.Request.Form [ "__ASYNCPOST" ] == "true");
String eventTarget = page.Request.Form [ "__EVENTTARGET" ];
if (page.IsPostBack == true)
{
//check if the postback control is not a button
if (String.IsNullOrEmpty(eventTarget) == false)
{
//all naming containers
String [] parts = eventTarget.Split('$');
foreach (String part in parts)
{
//find control on its naming container
control = control.FindControl(part);
}
}
else
{
//search all submitted form keys
foreach (String key in page.Request.Form.AllKeys.Where(k => Char.IsLetter(k [ 0 ])).ToArray())
{
//all naming containers
String [] parts = key.Split('$');
//initialize control to page on each iteration
control = page;
foreach (String part in parts)
{
//find control on its naming container
if ((part.EndsWith(".x")) || (part.EndsWith(".y")))
{
//ImageButton
control = control.FindControl(part.Substring(0, part.Length - 2));
}
else
{
//other button type
control = control.FindControl(part);
}
}
if (control is IPostBackEventHandler)
{
if (((control is ScriptManager) || (control is ScriptManagerProxy)) && (asyncPost == true))
{
//ScriptManager/ScriptManagerProxy themselves never fire postback events
continue;
}
else
{
//found firing event
break;
}
}
//clear control for next iteration
control = null;
}
}
}
return (control);
}
}