Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Finding out which control caused the Postback

0.00/5 (No votes)
2 Apr 2011 1  
This code is very useful for those who want to know which aspcontrol has caused the postback.

Introduction

There will be many instances where we would want to skip the (!IsPostBack), for which we have to know which control has triggered the postback, hence this code snippet.

Background

Add Global.asax to the project (right click project, add new item, add global).

Using the Code

The method GetPostBackControl should be written in Global.asax file (so that it is accessible globally across the application).

public class Global : System.Web.HttpApplication 
{ 
    public static System.Web.UI.Control GetPostBackControl(System.Web.UI.Page page) 
    { 
        Control control = null; string ctrlname = page.Request.Params["__EVENTTARGET"]; 
        if (ctrlname != null && ctrlname != String.Empty) 
        { 
            control = page.FindControl(ctrlname); 
        } // if __EVENTTARGET is null, the control is a button type and we need to 
          // iterate over the form collection to find it 
        else 
        { 
            string ctrlStr = String.Empty; 
            Control c = null; 
            foreach (string ctl in page.Request.Form) 
            { // handle ImageButton controls ... 
                if (ctl.EndsWith(".x") || ctl.EndsWith(".y")) 
                { 
                    ctrlStr = ctl.Substring(0, ctl.Length - 2); 
                    c = page.FindControl(ctrlStr); 
                } 
                else 
                { 
                    c = page.FindControl(ctl); 
                } 
                if (c is System.Web.UI.WebControls.Button || 
			c is System.Web.UI.WebControls.ImageButton) 
                { 
                    control = c; break; 
                } 
             } 
        } 
        return control; 
    } 
} 

This is very useful for tough web applications.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here