On postback, how can I check which control cause postback in Page_Init event.
protected void Page_Init(object sender, EventArgs e)
{
//need to check here which control cause postback?
}
Thanks
This question is related to
c#
asp.net
page-lifecycle
if (Request.Params["__EVENTTARGET"] != null)
{
if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID"))
{
DoWhateverYouWant();
}
}
If you need to check which control caused the postback, then you could just directly compare ["__EVENTTARGET"]
to the control you are interested in:
if (specialControl.UniqueID == Page.Request.Params["__EVENTTARGET"])
{
/*do special stuff*/
}
This assumes you're just going to be comparing the result from any GetPostBackControl(...)
extension method anyway. It may not handle EVERY situation, but if it works it is simpler. Plus, you won't scour the page looking for a control you didn't care about to begin with.
Assuming it's a server control, you can use Request["ButtonName"]
To see if a specific button was clicked: if (Request["ButtonName"] != null)
Here's some code that might do the trick for you (taken 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;
}
To get exact name of control, use:
string controlName = Page.FindControl(Page.Request.Params["__EVENTTARGET"]).ID;
An addition to previous answers, to use Request.Params["__EVENTTARGET"]
you have to set the option:
buttonName.UseSubmitBehavior = false;
Either directly in form parameters or
string controlName = this.Request.Params.Get("__EVENTTARGET");
Edit: To check if a control caused a postback (manually):
// input Image with name="imageName"
if (this.Request["imageName"+".x"] != null) ...;//caused postBack
// Other input with name="name"
if (this.Request["name"] != null) ...;//caused postBack
You could also iterate through all the controls and check if one of them caused a postBack using the above code.
Source: Stackoverflow.com