Thursday 11 June 2015

Use ViewState in diffrent page



If you want to use only viewstate to send data to next page, then you should use the server.transfer() method instead of resposnse.redirect() method. Let us suppose we want to pass viewstate on click of a button as below:

    public void btnSer_OnClick(object sender, EventArgs e)
    {

        ViewState["yourvalue"] = "sujoy santra";
        ViewState["yourcity"] = "kolkata";
        Server.Transfer("Default.aspx");

    }

on the same page create a method of the class statebag

     public StateBag ReturnViewState()
    {
        return ViewState;
    }

Now on the page where you want to transfer let here be Default.aspx. Place the following function in Default.aspx.cs file

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;
        }
    }

Now let us find the values of viewstate of previous page( ViewState["yourvalue"] and ViewState["yourcity"])

let us do it at page load of Default.aspx

    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null && PreviousPageViewState != null)
        {
            var sg = PreviousPageViewState["yourvalue"].ToString();
            var nev = PreviousPageViewState["yourcity"].ToString();
        }
    }

So we are done. you can access the viewstate value of previous page.

No comments:

Post a Comment