ASP.Net: How to Find Which Control Caused Postback?


At times in a webpage, we can have many controls that can possibly "Post-back". It can be a PITA to find which control actually posted back if the actual controls are dynamically created.
So to find exactly which control posted back, a code snippet is given below which should be added to the page_load method of webpage:

protected void Page_Load(object sender, EventArgs e)
{
 if (Page.IsPostBack)
 {
  //Creates the dynamic button. the methods is given below
  addSaveButton();
  string ctrlname = Page.Request.Params.Get("__EVENTTARGET");
  Control control = null;
  control = Page.FindControl(ctrlname);
  if (control == saveButton)
  //Do whatever you what to do!
 }
}

void addSaveButton()
{
 saveButton = new Button();
 saveButton.Text = "Save";
 saveButton.ID = "sb_1";
 saveButton.UseSubmitBehavior = false;
 saveButton.Command += new CommandEventHandler(saveButton_Click);
 saveButton.CommandName = "saveButton";
}
So that was a piece of cake...right!
But at time we can have a panel control which holds all those dynamically created tools such buttons and textboxes. So to traverse through all of them and to find the specific control, we have the following method that takes in container i.e. the panel control,  and the name of the control to be searched, as parameters:
public static Control FindControl(Control container, string name)
{
 if ((container.ID != null) &&(container.ID.Equals(name)))
 return container;
 foreach (Control ctrl in container.Controls)
 {
  Control foundCtrl = FindControlRecursive(ctrl, name);
  if (foundCtrl != null)
   return foundCtrl;
}

Hope this helps
Cheers
Vaqar Hyder

Comments

Popular posts from this blog

SPFx: Develop using SharePoint Framework without Installing all the dependecies.

SharePoint Online: Elevated Permissions....with love

Powershell: Filling up an Existing Excel Sheet with data from SQL Server