Embedd_0913
Embedd_0913

Reputation: 16555

Can I access ViewState of one page in another page in Asp.Net?

Is there a way to access viewstate of a page in another page ? Please elaborate the answer to clear my doubts as I think ViewState has it's scope to the page only and can't be accessed outside page.

Upvotes: 5

Views: 21032

Answers (3)

Neeraj Kumar Gupta
Neeraj Kumar Gupta

Reputation: 2363

This will also work

FirstPage.aspx (in code behind)

public void btnTransfer_Click(object sender, EventArgs e)
{
    CompanyInfo comInfo = new CompanyInfo() { ID = 223, Name = "TCS" };
    ViewState["ViewStateCompany"] = comInfo;     
    Server.Transfer("SecondPage.aspx");
}

public CompanyInfo  GetViewValue() 
{
    CompanyInfo comInfo = (CompanyInfo )ViewState["ViewStateCompany"];
    return comInfo;
} 

SecondPage.aspx (in code behind)

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.PreviousPage != null)
    {

        Type ty = Page.PreviousPage.GetType();
        MethodInfo mi = ty.GetMethod("GetViewValue");
        CompanyInfo comInfo = (CompanyInfo)mi.Invoke(Page.PreviousPage, null);

    }
}

CompanyInfo class

public class CompanyInfo
{
    public int ID { get; set; }
    public string Name { get; set; }
}

Upvotes: 0

Kamaraj mahalingam
Kamaraj mahalingam

Reputation: 41

Almost in all ASP.NET interview this question will be asked. The Answer for this questions no directly but we can access through statebag class. But calling the second page should be through server.transfer

FirstPage.aspx

    protected void Page_Load(object sender, EventArgs e)
    {
        ViewState["Name"] = "Kamaraj";
        Server.Transfer("SecondPage.aspx");

    }
    public StateBag ReturnViewState()
    {
        return ViewState;
    }

//Second Page
Secondpage.aspx

    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null && PreviousPageViewState != null)
        {
            lblMag.Text = PreviousPageViewState["Name"].ToString();
        }
    }

    private StateBag PreviousPageViewState
    {
        get
        {
            StateBag returnValue = null;
            if (PreviousPage != null)
            {
                Object objPreviousPage = (Object)PreviousPage;
                MethodInfo objMethod = objPreviousPage.GetType().GetMethod("ReturnViewState");//System.Reflection class
                return (StateBag)objMethod.Invoke(objPreviousPage, null);
            }
            return returnValue;
        }
    }

Upvotes: 4

rahul
rahul

Reputation: 187050

You can't access ViewState of one page from another page directly.

If you want to access a particular ViewState value then you can pass the value in Context collection and then access the value in other page.

In page 1

Context.Items.Add ( "variable" , ViewState["yourvalue"].ToString() );

In page 2

string myValue = Context.Items["variable"].ToString();

Upvotes: 10

Related Questions