On postback, how can I check which control cause postback in Page_Init event
I see that there is already some great advice and methods suggest for how to get the post back control. However I found another web page (Mahesh blog) with a method to retrieve post back control ID.
I will post it here with a little modification, including making it an extension class. Hopefully it is more useful in that way.
/// <summary>
/// Gets the ID of the post back control.
///
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
// first we will check the "__EVENTTARGET" because if post back made by the controls
// which used "_doPostBack" function also available in Request.Form collection.
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
// ReSharper disable TooWideLocalVariableScope
string controlId;
Control foundControl;
// ReSharper restore TooWideLocalVariableScope
foreach (string ctl in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property"
// in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is IButtonControl)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
Update (2016-07-22): Type check for Button
and ImageButton
changed to look for IButtonControl
to allow postbacks from third party controls to be recognized.
Which control caused the postback?
You can use this method to get the control that caused the postback:
/// <summary>
/// Retrieves the control that caused the postback.
/// </summary>
/// <param name="page"></param>
/// <returns></returns>
private Control GetControlThatCausedPostBack(Page page)
{
//initialize a control and set it to null
Control ctrl = null;
//get the event target name and find the control
string ctrlName = page.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(ctrlName))
ctrl = page.FindControl(ctrlName);
//return the control to the calling method
return ctrl;
}
How to check whether postback caused by a Dynamic link button
A postback in asp.net is done by the java script function __doPostback(source, parameter)
so in your case it would be
__doPostback("lnkDynamic123","") something like this
So in the code behind do the following
var btnTrigger = Request["__EVENTTARGET"];
if(btnTrigger=="lnkDynamic123")
{
}
--- this would tell that it is your linkbutton that causes the postback
Determining which control raised the postback
To check which control caused the postback, use Request.Form["__EVENTTARGET"]. This should return a unique ID of the control that caused the postback.
EDIT
For this to work you will have to set UseSubmitBehavior
property of the button to false which causes it to use Asp Net post back mechanism
Use the UseSubmitBehavior property to specify whether a Button control uses the client browser's submit mechanism or the ASP.NET postback mechanism. By default the value of this property is true, causing the Button control to use the browser's submit mechanism. If you specify false, the ASP.NET page framework adds client-side script to the page to post the form to the server.
When the UseSubmitBehavior property is false, control developers can use the GetPostBackEventReference method to return the client postback event for the Button. The string returned by the GetPostBackEventReference method contains the text of the client-side function call and can be inserted into a client-side event handler.
From MSDN
find out which control triggered postback
From:
http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
return this.Page.FindControl(ctrlname);
}
Get ASP.NET control which fired a postback within a AJAX UpdatePanel
Try the following method:
public string GetAsyncPostBackControlID()
{
string smUniqueId = ScriptManager.GetCurrent(Page).UniqueID;
string smFieldValue = Request.Form[smUniqueId];
if (!String.IsNullOrEmpty(smFieldValue) && smFieldValue.Contains('|'))
{
return smFieldValue.Split('|')[1];
}
return String.Empty;
}
The above method uses the hidden field of the ScriptManager on page. Its value can be accessed on the server by searching for a form key with the UniqueID of the ScriptManager. The value in the hidden field is in the format [UpdatePanel UniqueID]|[Postback Control ID]
. Knowing this information we can retrieve the ID of the control that initiated the asynchronous postback. And it works for submit buttons too.
ASP.NET Read Event in Page_Init
You can easily identify which control caused the event with something like:
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;
}
lifted from http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx
I've used this with success before although I've never actually needed event data - just knowledge of the event fired.
Related Topics
How to Sort an Observable Collection
Question Mark and Colon in Statement. What Does It Mean
How to Compare Values of Generic Types
Get Os Version/Friendly Name in C#
How to Backup and Restore the System Clipboard in C#
Restrict Access to a Specific Controller by Ip Address in ASP.NET MVC Beta
How to Flatten Nested Objects with Linq Expression
Is There Any Simple Way to Convert .Xls File to .CSV File? (Excel)
Error Accessing Com Components
How to Find the "Clamp" Function in .Net
One to One Optional Relationship Using Entity Framework Fluent API
How to Find All Implementations of an Interface
Play and Wait for Animation/Animator to Finish Playing
Wpf: How to Override Part of a Controltemplate Without Redefining the Whole Style
How to Get the Name of the Current Executable in C#