Sunday, May 25, 2008

Which control causes the PostBack

In the page life cycle the Click event, SelectedIndexChanged event and other events raised by the UI controls are called after Page_Load event. But in many case we need to know which control causes the post back in Page_Load/Init function. If we are working with dynamic controls or other complex UI then this information we often need.
To determine if a control causes the Postback or not we can use the following function:

private Boolean CheckIfTheControlCausesPostBack(Control ctr)
{
   String ctrID = this.Page.Request.Params["__EVENTTARGET"];
   if (ctrID != null && ctrID != "")
   {
      String newctrID = ctrID.Replace("$", "_");
      if (newctrID == ctr.ClientID)
      return true;
   }
   else if (ctr.GetType().ToString() == "System.Web.UI.WebControls.ImageButton" || ctr.GetType().ToString() == "System.Web.UI.WebControls.Button")
   {
      String controlID = ctr.ClientID;
      String controlIDX = ctr.ClientID + ".x"; 
      String controlIDY = ctr.ClientID + ".y";
      foreach (String key in this.Page.Request.Form.AllKeys)
      {
         String newKey = key.Replace("$", "_");
         if (newKey == controlID || newKey == controlIDX || newKey == controlIDY)
         {
            return true;
         }
      }
    }
    return false; 
}

Understanding Code:
In most cases, this.Page.Request.Params["__EVENTTARGET"] contains the ID of control that causes Postback. But for Button and ImageButton the property remains empty string. Rather the control ID can be found in this.Page.Request.Form.AllKeys collection. So we have to loop through the collection and find if the ID exists. Notice I am concatenating “.x” and “.y” with control ID. This is because if the control is ImageButton then in that collection it contains ControlID + “.x” and ControlID + “.y” rather than ControlID.

And I am also replacing “$” sign with “_”, because if the control contains in other container (Panel, UserControl etc) then the ClientID of that control is ContainerID1_ContainerID2_ControlID; whereas in the collection it contains ContainerID1$ContainerID2$ControlID. So we have to replace that symbol before comparing.

To know more about Page Life Cycle: ASP.NET Page Life Cycle Overview

No comments:

Post a Comment