Sunday, November 22, 2015

ASP.NET - Get Postback Control

Sometimes we need to detect which control caused the postback and following method can be used to get the control in ASP.Net


     public static string GetPostBackControlId(this Page page)  
     {  
       if (!page.IsPostBack)  
         return string.Empty;  
       Control control = null;          
       string controlName = page.Request.Params["__EVENTTARGET"];  
       if (!String.IsNullOrEmpty(controlName))  
       {  
         control = page.FindControl(controlName);  
       }  
       else  
       {           
         string controlId;  
         Control foundControl;           
         foreach (string ctl in page.Request.Form)  
         {             
           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 Button || foundControl is ImageButton)) continue;  
           control = foundControl;  
           break;  
         }  
       }  
       return control == null ? String.Empty : control.ID;  
     }  

No comments:

Post a Comment