Thursday, September 15, 2011

Getting Previous Page's control that caused postback in current page

First checking normal postback or crosspage postback:
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
       // Do Something}

Previous Page Aspx:
  <asp:LinkButton ID="LnkID" runat="server" PostBackUrl="" Text="Link to New Page" />

We must use "PostBackUrl"  property here

Current Page CS:
page_load
{
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
         Control LnkCtrl = GetPostBackControl(this.Page);
         string ctrlID = LnkCtr.ID;
    }
}

private Control GetPostBackControl(Page page)
        {
            Control control = null;

            string ctrlname = page.Request.Params.Get("__EVENTTARGET");
            if (ctrlname != null && ctrlname != string.Empty)
            {
                control = page.PreviousPage.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;
        }

No comments:

Post a Comment