Wednesday, February 15, 2012

Reading and writing into ViewState

Here is a asimple example of ViewState. Add a button (btnShow) and Label (lblShow to ypur markup and add the following code to your code-behind file
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ViewStateExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            lblShow.ForeColor = (System.Drawing .Color )ViewState["Forecolor"];//reading from viewstate
        }
        else
        {
            lblShow.ForeColor = System.Drawing.Color.DarkViolet;
            ViewState["Forecolor"] = lblShow.ForeColor;//writing into viewstate
        }
    }
    protected void btnShow_Click(object sender, EventArgs e)
    {
        lblShow.Text = "Hey GOOOD MORINING :-)";
    }
}

No comments:

Post a Comment