ASP.NET 2.0 - ViewState not working???

G

Guest

I am testing ViewState in a C# ASP.NET site. The following code SHOULD cause
the values of the variables to increase whenever the user pushes the submit
button - but this is not happening; instead the values are getting set back
to their initial values set at page_load. Someone please tell me what I am
doing wrong!

Here is the code:

public partial class _Default : System.Web.UI.Page
{
Int32 Counter;
string StringVar;
double DoubleVar;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Counter = 1;
StringVar = "Hello";
DoubleVar = 3.5;
ShowCounter.Text = Convert.ToString(Counter);
ShowStringVar.Text = StringVar;
ShowDoubleVar.Text = Convert.ToString(DoubleVar);
}
else
{
Counter = (Int32)ViewState["Counter"];
StringVar = (string)ViewState["StringVar"];
DoubleVar = (double)ViewState["DoubleVar"];
}
}

void Page_PreRender(object Sender, EventArgs e)
{
ViewState["Counter"] = Counter;
ViewState["StringVar"] = StringVar;
ViewState["DoubleVar"] = DoubleVar;
}

void PushMe_Click(Object sender, EventArgs e)
{
Counter = Counter + 1;
StringVar = StringVar + "!";
ShowCounter.Text = Convert.ToString(Counter);
ShowStringVar.Text = StringVar;
ShowDoubleVar.Text = Convert.ToString(DoubleVar);
}
}
 
G

Guest

Cade said:
I am testing ViewState in a C# ASP.NET site. The following code SHOULD cause
the values of the variables to increase whenever the user pushes the submit
button - but this is not happening; instead the values are getting set back
to their initial values set at page_load. Someone please tell me what I am
doing wrong!

Here is the code:

public partial class _Default : System.Web.UI.Page
{
Int32 Counter;
string StringVar;
double DoubleVar;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Counter = 1;
StringVar = "Hello";
DoubleVar = 3.5;
ShowCounter.Text = Convert.ToString(Counter);
ShowStringVar.Text = StringVar;
ShowDoubleVar.Text = Convert.ToString(DoubleVar);
}
else
{
Counter = (Int32)ViewState["Counter"];
StringVar = (string)ViewState["StringVar"];
DoubleVar = (double)ViewState["DoubleVar"];
}
}

void Page_PreRender(object Sender, EventArgs e)
{
ViewState["Counter"] = Counter;
ViewState["StringVar"] = StringVar;
ViewState["DoubleVar"] = DoubleVar;
}

void PushMe_Click(Object sender, EventArgs e)
{
Counter = Counter + 1;
StringVar = StringVar + "!";
ShowCounter.Text = Convert.ToString(Counter);
ShowStringVar.Text = StringVar;
ShowDoubleVar.Text = Convert.ToString(DoubleVar);
}
}

Never mind - I figured out the problem.......I hadn't wired up the button to
the PushMe_Click subroutine. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top