Loading ...

How to find which control has caused the postback on the page

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  web forms / data controls   » How to find which control has caused the postback on the page

How to find which control has caused the postback on the page

Posts under the topic: How to find which control has caused the postback on the page

Posted: 5/20/2010

Lurker 235  points  Lurker
  • Joined on: 10/16/2009
  • Posts: 47

I need to find the control which has caused the postback on my page. I am working in c# please help me.


tags c#

Posted: 5/20/2010

Contributor 2255  points  Contributor
  • Joined on: 11/30/2008
  • Posts: 11
  Answered

kevin said:

I need to find the control which has caused the postback on my page. I am working in c# please help me.

 

Hi Kevin,

 Try the following code:

 

protected void Page_Load(object sender, EventArgs e)
        {
         //on every postback you can print the ID of the control which caused postback
            if (IsPostBack)
            {
                Control ctl = GetPostBackControl(Page);
                if (ctl != null)
                    Response.Write(ctl.ID);
            }
        }

//method that Identify the postback control
public static 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;
        }

let me know if its not working..


Posted: 5/21/2010

Guru 16813  points  Guru
  • Joined on: 4/19/2009
  • Posts: 490
  Answered

Simply stick to string controlID = Request.Params["__EVENTTARGET"]; as you don't know whether it is Button, ImageButton , LinkButton, DropDown or else.. which has caused the postback.


tags c#
Page 1 of 1 (3 items)