Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

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);
	}
}
Bookmark and Share
Posted: Jan 26 2010, 02:21 PM by Ricardo Peres | with 2 comment(s)
Filed under: ,

Comments

Yonggang Meng said:

This is helpful!

# March 19, 2010 1:54 AM

koolraagaa said:

Sweet !!! Thank you very much. Quite Elegant.

# March 25, 2010 9:48 PM