Jeremy Beare
Jeremy Beare

Reputation: 487

C# and ASP - Retaining Variable Value on Button Click

I am working on a warning system for another person's website. The premise is simple enough, if the conditions are met and the warningFlag variable is set "", the warning is made and the warningFlag variable is set to "Y".

However it never retains the value and always triggers the warning. I have tried the ViewState and it would not work. Bit confused as to why it would not work as the ViewState should have done the trick. Maybe I am missing something? Can you help out an ASP beginner?

Page_Load

if (ViewState["warningFlag"] == null)
    ViewState.Add("warningFlag", ""); //Add the flag
else
    ViewState["warningFlag"] = ""; //Reset the flag

Button click event

if (ViewState["warningFlag"].ToString() == "")
{
    if (this.checkForWarning()) //Checks if Warning conditions are met
    {
        ViewState["warningFlag"] = "Y";

        //Warning Message Code goes here
        return;
    }
}

Upvotes: 1

Views: 747

Answers (1)

Royi Namir
Royi Namir

Reputation: 148744

Line 2,4 are doing the same thing(not 100% , but with the same final result)

if (ViewState["warningFlag"] == null)
    ViewState.Add("warningFlag", ""); //Add the flag
else
    ViewState["warningFlag"] = ""; //Reset the flag

If you want to stop getting the Warning do this :

if (ViewState["warningFlag"] == null)
    ViewState.Add("warningFlag", "");  
else
    ViewState["warningFlag"] = "x"; //<-------- see this

Edit ( after comment)

So change to this :

if (ViewState["warningFlag"] == null)
    ViewState.Add("warningFlag", ""); //Add the flag
else

if (ViewState["warningFlag"].ToString() !="Y")
     ViewState["warningFlag"] = ""; //Reset the flag

Upvotes: 1

Related Questions