Click here to Skip to main content
Click here to Skip to main content

How to know which control has raised a postback?

, 19 May 2010
Rate this:
Please Sign up or sign in to vote.
Identifying the control that raised postback event
Sometimes we may need to know the source of postback. Our purpose of knowing the source may be like doing diverse activities depending which control or what type of control raised the postback. Inorder to identify the control that had raised the postback we can do something as simple as:
 
1. In the Page_Load event check whether its a postback or not-
 
protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
           lblControl.Text=GetPostBackControl(this);
 
        }
        
    }
 
2. Next we define the GetPostBackControl() method as below: -
 
public string GetPostBackControl(System.Web.UI.Page page)
    {
        Control ctrl1 = null;
        Control ctrl2 = null;
        string ctrlName = page.Request.Params["__EVENTTARGET"];
        string ctrlStr = string.Empty;
        if (ctrlName != null && ctrlName != String.Empty)
        {
            ctrl1 = page.FindControl(ctrlName);
        }
        else
        {
            foreach (string ctl in page.Request.Form)
            { 
                if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                {
                    ctrlStr = ctl.Substring(0, ctl.Length - 2);
                    ctrl2 = page.FindControl(ctrlStr);
                }
                else
                {
                    ctrl2 = page.FindControl(ctl);
                }
                if (ctrl2 is System.Web.UI.WebControls.Button || ctrl2 is System.Web.UI.WebControls.ImageButton)
                {
                    ctrl1 = ctrl2; 
                    break;
                }
            }
        }
 
        return ctrl1.ClientID;
    }
 
To test the code -
  1. Place a number of controls that raises postback in a page.
  2. Place a label (lblControl in this code snippet) to display the control id that raised the postback.
  3. For the controls that need it set autopostback property to true.
 

Now test the code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

girlprogrammer
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 19 May 2010
Article Copyright 2010 by girlprogrammer
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid