How to Identify Postback event in Page_Load

前端 未结 3 758
滥情空心
滥情空心 2020-12-11 06:53

We have some legacy code that needs to identify in the Page_Load which event caused the postback. At the moment this is implemented by checking the Request data like this...

相关标签:
3条回答
  • 2020-12-11 07:19

    In addition to the above code, if control is of type ImageButton then add the below code,

    if (control == null) 
    { for (int i = 0; i < page.Request.Form.Count; i++) 
        { 
            if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y"))) 
                 { control = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2)); break; 
                 }
         }
     } 
    
    0 讨论(0)
  • 2020-12-11 07:30

    This should get you the control that caused the postback:

    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;
    }
    

    Read more about this on this page: http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx

    0 讨论(0)
  • 2020-12-11 07:30

    I am just posting the entire code (which includes the image button / additional control check that causes postback). Thanks Espo.

    public 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; }
               }
           }
    // handle the ImageButton postbacks 
    if (control == null) 
    { for (int i = 0; i < page.Request.Form.Count; i++) 
        { 
            if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y"))) 
                 { control = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2)); break; 
                 }
         }
     } 
    return control; 
    }
    
    0 讨论(0)
提交回复
热议问题