Link to home
Start Free TrialLog in
Avatar of rito1
rito1

asked on

How to make a variable available within multiple events

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

ASKER CERTIFIED SOLUTION
Avatar of johnaryan
johnaryan
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rito1
rito1

ASKER

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.
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.


Avatar of rito1

ASKER

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.