Wednesday 9 December 2015

How to pass repeater/any control from one page to another in asp.net?


Step 1:

 Make two pages, one where the control (repeater) is present and another where you need to transfer it, namely source.aspx and destination.aspx.


Step 2:

At source.aspx page write down your control (repeater) and bind it, in my case i am passing the repeater, so that i could print it on another page, you can have other cases to use this functionality..

So at design page of source.aspx

<asp:Repeater ID="rptSalary" runat="server">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>

<asp:Button ID="btnPrint" runat="server" Text="Print Slip"

onclick="btnPrint_Click" />


At source.aspx.cs

On button click event at which you need this control (repeater) to move to another page.

protected void btnPrint_Click(object sender, EventArgs e)
{
Server.Transfer("~/destination.aspx");
}



Step 3:

At destination.aspx page add all the css file which you might have used at source.aspx, to get the style as well

At destination.aspx.cs page where we code c#, do the following code to find the specific control (repeater in our case) from the source.aspx page


protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.PreviousPage != null)
{
Control ContentPlaceHolder1 = this.Page.PreviousPage.Master.FindControl("ContentPlaceHolder1");
Repeater rptSalary = (Repeater)ContentPlaceHolder1.FindControl("rptSalary");

}
}

Now, if add this rptSalary instance of repeater to any control on this page, or create that too dynamically as below :


Panel Panel1 = new Panel();
Panel1.Controls.Add(rptSalary);
Page.Controls.Add(Panel1);


Now, we have successfully passed the control to another page.
And yeah if you too want to print this repeater or any specific control from a webpage, then follow this whole procedure and just add one more line to it i.e ,

Response.Write("<script>window.print();</script>");



The whole code for destination.aspx will be;



protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.PreviousPage != null)
{
Control ContentPlaceHolder1 = this.Page.PreviousPage.Master.FindControl("ContentPlaceHolder1");
Repeater rptSalary = (Repeater)ContentPlaceHolder1.FindControl("rptSalary");
Panel Panel1 = new Panel();
Panel1.Controls.Add(rptSalary);
Page.Controls.Add(Panel1);
Response.Write("<script>window.print();</script>");
}
}


No comments:

Post a Comment