Zebra0.com

visual-basic variables

Let's suppose we want a program that will count the number of times you click a button.
The code shown below will not work because the value of counter is reset to 0 each time the function executes.

private void btnGo_Click(object sender, EventArgs e)
{
int counter = 0;
counter++;
this.Text = "" + counter;
}

Instead, we need to make the variable global by declaring it outside of any function so that the value is maintained throughout the execvution of the program:

namespace variables
{
    public partial class Form1 : Form
    {
        int counter = 0; //global
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            counter++;
            this.Text = "" + counter;
        }
    }

NEXT: Variables