rathi bond
rathi bond

Reputation: 81

How to count by one on a Windows form Application (C# Visual Studio)

I have a school project that wants me to make a windows Form Application in C#. Each time I click the button It should add 1.

This was my first idea, but it says "Use of unsigned local variable. If I set z to 0 at the start the problem is it resets it each time I click the button. Any ideas?

int z;
z = z + 1;
txtBox.text = z.ToString();

I hope this makes sense. I am new to asking these types of questions online. Thank you

Upvotes: 0

Views: 3235

Answers (3)

Lyber
Lyber

Reputation: 157

This should work !

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    int z;

    private void button1_Click(object sender, EventArgs e)
    {
        z = z +1;
        txtBox.Text = z.ToString();
    }
}

Upvotes: 0

Luiz Claudio Ramos
Luiz Claudio Ramos

Reputation: 46

You are declaring the 'z' variable inside the button click event scope, try declaring it just above the onClick method, also make sure to initialize it as 0

int z = 0;
private void Button_Click...

Upvotes: 3

Dave
Dave

Reputation: 1

I'm assuming the code you provided is inside the "Button_click" method that was created by you double clicking on the button in the form designer.

The problem is that z needs to be declared outside that method, otherwise, as you noted is re-initialized to 0 every time you click the button.

Upvotes: -1

Related Questions