Form level variable scope issue

G

Guest

I have a C# Web application that has 1 Web form that has 2 command buttons on
it with a label for output. I have a form level variable declared String
strName = "Jim"; right below where the buttons are declared by the form
designer. I have two event methods for my 2 command buttons. In the
Button1_Click event method I change the value of the form level variable
strName = "Kevin";. In the second event method, Button2_Click I check to see
if strName == "Jim", if so the label displays "failure", but if strName ==
"Kevin" the label displays "success".

Now, when I click on Button1, then click on Button2 the label displays
"failure". Why is my form level variable getting cleared out on the post
back? I have three different applications that are showing the same
symptoms. Please, can somebody shed some light?
 
J

Joyjit Mukherjee

Hi,

That is the inherent nature of Internet applications, they are stateless. So
whatever variables you're setting at the form level, are recreated at each
postbacks with default values. If you need the variable to persist across
postbacks, consider adding it to Viewstate so that you can retrieve it
later.

regards
Joyjit
 
S

Steve C. Orr [MVP, MCSD]

That's just how it works.
If you want to store values between postbacks you need to store the value
manually.
In this case it sounds like you want a page scoped variable, so ViewState
would likely be your best option.
In Button1's click event put code like this:
ViewState("Name")="Jim"

Then in button2's event put code like this:
If ViewState("Name").ToString = "Kevin" then 'display success

You could use Session scope (with similar syntax) if you'd like this value
to be visible to other pages for that user.
 

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

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top