Overblog Follow this blog
Edit post Administration Create my blog
Balavardhan Reddy Narani

How to Access ViewState Across Pages

August 25 2009 , Written by Balavardhan Reddy Published on #ASP.Net

Access ViewState Across Pages

We can access the viewstate variables across pages. This is possible when we use Cross Page Posting or Server.transfer to redirect the other pages

Ex :
Here I have created two aspx pages named:

   1. First.aspx: This page sets the ViewState variable and transfers the user to another page by using the Server.transfer.
   2. Second.aspx: This page accesses the ViewState variable of First.aspx page.

First.aspx :

public partial class First : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ViewState["Page1"] = "My First page";
        Server.Transfer("Second.aspx");
    }

    public StateBag FirstViewState()
    {
        return ViewState;
    }
}



StateBag class: This class is the primary storage mechanism for all HTML and Web server controls. It stores attribute/value pairs as strings associated with the control. It tracks changes to these attributes only after the OnInit method is executed for a page request, and saves the changes to the page's or control's viewstate.


Second.aspx :

public partial class Second : System.Web.UI.Page
{
    private StateBag firstPageViewstate
    {
        get
        {
            StateBag returnValue = null;
            if (PreviousPage != null)
            {
                Object objPreviousPage = (Object)PreviousPage;
                MethodInfo objMethod = objPreviousPage.GetType().GetMethod                                             ("FirstViewState");
                return (StateBag)objMethod.Invoke(objPreviousPage, null);
            }
            return returnValue;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null)
        {
            if firstPageViewstate != null)
            {
                Label1.Text = firstPageViewstate["Page1"].ToString();
            }
        }
    }
}



Using Previous Page, we can find the controls of the previous page. For example, one can access Label control placed in ViewStateContainer Page in current Page.




--

Share this post

Repost 0

Comment on this post

Adam R 03/07/2012 20:45


Thank your very much for this great tutorial, I have been looking for this for hours and finally found it on your blog.


--------------------------------


jak szybko schudnac

Dissertation Writing 02/27/2010 10:49


I love your blog so much, and there are just some differences with others'. Hope there will be more wonderful things in your blog. Happy every day!
----------------------
Dissertation Writing