Simple clicker with button using Visual Studio

63 Views Asked by At

I have a problem. So i was trying to do simple cliker using button: it counts button clicks. I was searching it on internet and tryed this code:

{
    int intClicks = 0;
    intClicks++;
    for (int i = 0; i < 10; i++) { 
        Lab1.Text = ("button has been clicked " + intClicks + (intClicks == 1 ? " time." : " times."));
    }
}

But it only count once. I don't have idea how to reapiar this.

I want it to count EVERY button click.

1

There are 1 best solutions below

0
Auditive On

As @Good Night Nerd Pride mentioned, you "forgetting" clicks count by resetting it to 0 at each button click.

To "remember" clicks count, your int variable should be declared somewhere out of Button.Click event handler scope.

From "Lab1.Text" i decided that you using Windows Forms (Label control with Text property), so declaring int variable to "remember" total clicks count out of Button.Click event handler may look like this:

public partial class Form1 : Form
{    
    // ... some other stuff

    private int _totalClicks;

    private void Button_Click(object sender, EventArgs e)
    {
        _totalClicks++;
        Lab1.Text = $"Button has been clicked {_totalClicks} {(_totalClicks == 1 ? "time" : "times")}";
    }

And when you need to reset it - you probably want some other Button, which sets _totalClicks variable to 0 (and clears Label.Text if needed):

private void ButtonReset_Click(object sender, EventArgs e)
{
    _totalClicks = 0;
    Lab1.Text = string.Empty;
}