Posted: 5/20/2010
I need to find the control which has caused the postback on my page. I am working in c# please help me.
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
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.