I have a boolean variable called CheckBoxActivated that I assign to true after validating a user name and password.
string name = us.UserName;
string password = us.Password;
if (name.Equals(txtName.Text) && (password.Equals(txtPassword.Text)))
{
CheckBoxAvtivated = true;
The strange thing is,after assigning 'true' to the variable I click another button and immediately it becomes 'false' which results in undesired behaviour.
protected void butNext_Click(object sender, EventArgs e)
{
if (CheckBoxAvtivated)
{
pnlCheckBoxes.Visible = true;
pnlUserCheckBoxValidation.Visible = false;
}
else
{
pnlCheckBoxes.Visible = false;
pnlUserCheckBoxValidation.Visible = true;
}
The state of the variable thus changes to false unexpectedly. Any reason why this could happen?
The class level variables (global variables) in asp.net does not maintain state between postbacks you have to use viewstate if you want to keep the state between postbacks. ASP.NET is based on the HTTP protocol, which is stateless protocol and provides no means of storing a user's data between requests
To set in viewstate
ViewState["CheckBoxAvtivated"] = "true";
To get from viewstate
bool CheckBoxAvtivated = bool.Parse(ViewState["CheckBoxAvtivated"].ToString());
It is important to learn where to use viewstate and where it should not be used.
View state's purpose in life is simple: it's there to persist state across postbacks. (For an ASP.NET Web page, its state is the property values of the controls that make up its control hierarchy.) This begs the question, "What sort of state needs to be persisted?" To answer that question, let's start by looking at what state doesn't need to be persisted across postbacks. Recall that in the instantiation stage of the page life cycle, the control hierarchy is created and those properties that are specified in the declarative syntax are assigned. Since these declarative properties are automatically reassigned on each postback when the control hierarchy is constructed, there's no need to store these property values in the view state.
From MSDN.
In computing, a stateless protocol is a communications protocol that treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of requests and responses. A stateless protocol does not require the server to retain session information or status about each communications partner for the duration of multiple requests. In contrast, a protocol which requires the keeping of internal state is known as a stateful protocol.
From Wikipedia
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With