We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

How to make a variable available within multiple events

rito1
rito1 asked
on
Medium Priority
296 Views
Last Modified: 2012-05-07
Hi All,

This is probably simple but the brain is really slow today.. blaming it on the heatwave!..

Within my code-behind I have a page_load and button_click event.

How can I declare a variable, assign a value to the variable within the PAGE_LOAD event and that value be available for me within the BUTTON_CLICK event?

many thanks,

Rit
protected void Page_Load(object sender, EventArgs e)
{
assign variable
}
 
protected void ButtonAddBasket_Click(object sender, ImageClickEventArgs e)
{
use variable value
}

Open in new window

Comment
Watch Question

Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Geoff BryanDeveloper
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks both. They both seem viable solutions.. is there much difference between the 2 or do you feel it is fair to split the points?

Rit
Whichever you prefer.

vbgb's solution is the more correct method, if no posting back is involved.

My method assumed you needed to persist data between calls.
Geoff BryanDeveloper

Commented:
I am happy for you to split - although my method also works when posting back as in order to run the server side button click event, the page load happens as well, with Page.IsPostBack = True

This works for a static value that you wish to set in the load event and then use in the button click. If the button click value might need to be different you would need to use viewstate (either as John suggests or by persisting the value in a hidden field on the page) if the value may not always be the same each time

In the latter case you would only initialise the variable in the page load when Page.IsPostback is False. Then, if some other event changes it, it is not reset (in this case to 'Hello World') on every postback.


Author

Commented:
HI Both, I have found both solutions extremely valuable for different situations now that I understand the differences so if you don't mind I have split it.

Many thanks both.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.