Bennett
Bennett

Reputation: 738

How can I count how many buttons have been pressed in my windows form?

I found a snippet of code from a similar question but it didn't quite fit my implementation, and I couldn't figure out how to adapt it to my game. I have fifteen buttons and I need to be able to count the number of buttons pressed for each turn of a game. I am a very much a beginner with a limited knowledge of programming. I need to be able to count button presses, and then have the method restart at each players turn.

private void label1_MouseClick(object sender, MouseEventArgs e)
{
    int count++;
}

I created mouse click event but I get an error when trying to increment my count int.

Upvotes: 2

Views: 3787

Answers (3)

qwr
qwr

Reputation: 3670

Simple fix.//all these inside form class

  //declare count as integer, you can also initialize it ( int count=startvalue;)
   int count;

   //if you want to understand read topic about delegates and events
   private void label1_MouseClick(object sender, MouseEventArgs e)
   {
      ++count;
   }

   //call reset()  when you want to reset
   private void reset(){
         count=0;
   }

Also check
stackoverflow: c# Resources, Books

Upvotes: 3

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

Use this class, then you can use ButtonEx instead of Button in your designer

public class ButtonEx : Button
{
    public int ClickCount { get; private set; }
    public ButtonEx()
    {
        this.Click += (s, e) => { ++this.ClickCount; };
    }

    public void ResetPressCount()
    {
        this.ClickCount = 0;
    }
}

I see you have used label instead of button in you application you can just use this for label

public class LabelEx : Label
{
    public int ClickCount { get; private set; }
    public LabelEx()
    {
        this.MouseClick += (s, e) => { ++this.ClickCount; };
    }

    public void ResetPressCount()
    {
        this.ClickCount = 0;
    }
}

Upvotes: 3

Onel Sarmiento
Onel Sarmiento

Reputation: 1626

Because int count++ is Invalid Syntax.

The proper way to create an Increment integer value is;

private int count = 0;
private void label1_MouseClick(object sender, MouseEventArgs e)
{
    count++;
}

and to reset the integer count you need to make a reset button or include the count = 0; in your desire method.

Upvotes: 2

Related Questions