I have a boolean variable declared at the top of a class and when a radio button is selected on a page, the variable gets set to true, but when the page is reloaded, the variable gets reset back to false. One way I have handled this was by using the static keyword, but I am not sure if this is the best way to handle this. Here is the class where I tried doing things in the Page_Load event, but it is still resets the variables to false.
public class SendEmail { bool AllSelected; protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { AllSelected = false; } } protected void rbAll_SelectedIndexChanged(object sender, EventArgs e) { if(rbAll.SelectedValue == 'All') AllSelected = true; } public Send() { if(AllSelected) { //Send Email. Never runs because AllSelected is always false; } } }
When the page gets reloaded, a new instance of your page class is created so any values from the last server interaction are lost. Put the value into viewstate if you want it to persist across postbacks:
The ViewState collection is written in a hidden element into the form in the client’s browser, and posted back and restored the next time they click a button or do any other ‘postback’ type action.