Home > Back-end >  I want to create a program that automatically updates the maximum value when I press the button
I want to create a program that automatically updates the maximum value when I press the button

Time:11-01

enter image description here

I'm sorry to ask you a basic question first. It hasn't been long since I learned C#.


 private void numberButton_Click(object sender, EventArgs e)
    {
        Random rand = new Random();

        int randNumber = rand.Next(1, 1000);

        randomNumber.Text = randNumber.ToString();

        bestScoreLabel.Text = randomNumber.Text;
    }

How can I implement the function so that the maximum value of the bestScoreLabel is automatically updated when I click the number button as shown in the picture above?

Currently, the code is configured as above, but the problem occurs that the maximum and current values are the same output.

CodePudding user response:

The idea is to have a variable to keep tracking the max number.

 private static int _maxNumber = 0;

 private void numberButton_Click(object sender, EventArgs e){
   Random rand = new Random();
   int randNumber = rand.Next(1, 1000);
   randomNumber.Text = randNumber.ToString(); 

   if (_maxNumber < randNumber)
   {
      _maxNumber = randNUmber;
   }
   bestScoreLabel.Text = _maxNumber.ToString();
  }
  •  Tags:  
  • c#
  • Related