Hi,
In this post, i will explain how to get gridview control defined in one page into another page. This is accomplished with "Page.PreviousPage" property.
Let Page1.aspx contains a gridview control and we want this gridview (or any object) be passed to another page called page2.aspx.
We try this goal in two alternatives ways:
- Button with PostBackUrl="Page2.aspx" attribute.
- Server.Transfer("Page2.aspx", true); by coding.
In page1.aspx define:
- Gridview control named - grid
- Button with postbackUrl="page2.aspx" - btn1
- and another Button with click-event - btn2
Markup:
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false" />
<hr/>
<asp:Label runat="server" Text="Testing Gridview access to next-Page, try below buttons"></asp:Label>
<br />
<asp:Button ID="btn1" runat="server" PostBackUrl="Page2.aspx" Text="NextPageDirect" />
(or) serverTransfer:
<asp:Button ID="btn2" runat="server" Text="NextPageAtServer" OnClick="btn2_Click" />
Code:
//Testing Gridview data access from one page to next page.
public partial class Page1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid(); //Your logic to fill gridview
}
}
public GridView Getgrid
{
get { return this.grid; } //ViewState should be enabled for gridview.
}
protected void btn2_Click(object sender, EventArgs e)
{
Server.Transfer("Page2.aspx", true);
}
}
In Page2.aspx define:Form control (default markup added by VS)
Code:
public partial class Page2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page1 pg = Page.PreviousPage as Page1;
if (pg != null)
{
GridView grid = pg.Getgrid;
form1.Controls.Add(grid);
}
}
}
Now Open the Page1.aspx from browser (or, run from VisualStudio).
Above is the screenshot of Page1.aspx
Page2 screenshot after button click in Page1Using the above technique and custom public properties, we can access any object from page1 to page2.