Search code examples
c#asp.netwebforms

How to use variables from a protected method in another method


I am attempting to recreate a C# Console Application I made, but in ASP.Net Web Forms this time, but I've been having a bit of trouble with my buttons.

I made 2 buttons, one to initialize a variable with a value, and the other to use said variable's value, but when I attempt to use the variable I receive an error saying that the variable does not exist in the current context.

Here is an example of what my code looks like:

protected void Button1_Click(object sender, EventArgs e)
{
    int answer = 5;
}

protected void Button2_Click(object sender, EventArgs e)
{
    if (Convert.ToInt32(txtAnswer.Text) == answer)
    {
        lblQuestion.Text = "You're Right!";
    }
}

Solution

  • Your answer variable is local to the click event handler. It does not exist outside of it. You have to define a field:

    int answer;
    protected void Button1_Click(object sender, EventArgs e)
    {
        answer = 5;
    }
    

    As a general rule: Everything inside curly braces is visible only within those braces (except when you can define a visibility, like public or internal). This is called scope.

    Note that the value is lost once the page has been sent. If you want to preserve the value across requests you have to store the value in a more permanent way, for example in the view state.