Let's say I have a user control with a couple of buttons. I'd like to know which one caused the postback, using this method from Ryan Farley's blog:
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
And this is how I am calling it:
string btn = GetPostBackControl(this.Page).ID;
I'm getting
Object reference not set to an instance of an object.
I know now that the problem comes from the fact that I'm using this.Page
, which represents the parent page.
How to reference the user control that I'm in? (not the parent page) So that it can work with the method to find the button that caused the postback?
Both buttons are located inside the user control. GetPostBackControl()
is also in the code-behind of the user control.
I did a quick example on your given code and it worked out pretty fine. Perhaps you did miss checking for Page.IsPostBack
? Obviously there will only be a postBackControl if there is a postBack...
@Buttons - they will be rendered as <input type="submit">
so they won't appear within ___EVENTTARGET
. That's why Ryan Farlay wrote in the blog post Determining the Control that Caused a PostBack:
[...] However, you can still get to it, just in a different way. Since the button (or input) is what causes the form to submit, it is added to the items in the Form collection, along with all the other values from the submitted form. [...] If you were to look in the Form collection for anything that is a button then that will be what caused the postback (assuming that it was a button that caused the page to submit). If you first check the __EVENTTARGET, then if that is blank look for a button in the Form collection then you will find what caused the postback
(emphasis mine)
With this code,
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Control postBackControl = GetPostBackControl(this.Page);
Debug.WriteLine("PostBackControl is: " + postBackControl.ID);
}
}
Call the code from Ryan's blog:
public static Control GetPostBackControl(Page page) { Control control = null; string ctrlname = page.Request.Params.Get("__EVENTTARGET"); if (ctrlname != null && ctrlname != string.Empty) { control = page.FindControl(ctrlname); } else { foreach (string ctl in page.Request.Form) { Control c = page.FindControl(ctl); if (c is System.Web.UI.WebControls.Button) { control = c; break; } } } return control; }