How do I make it so when i click a button a random form from 1-3 apears.

Lucky Raji 1 Reputation point
2022-09-01T12:10:21.837+00:00

I am working on a character selector and I want it so the user to have the ability to randomly select and character from a click of a button.
Thank you soo much ;)

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,864 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 50,026 Reputation points
    2022-09-01T13:48:44.55+00:00

    Use Random to randomly select a value. Suppose you have 3 characters to choose from. Then you'd do something like this.

       //Do this once at startup of your app or when creating the instance that handles the random logic  
       var random = new Random();  
         
       //Select 1 of 3  
       var selectedValue = random.Next(1, 4);  
    

    This would give all 3 equal chances of selection. Just wrap that code in the Click handler of the button (or in a helper type depending upon your app needs).

       private void OnSelectCharacter ( object sender, EventArgs e )  
       {  
          //Assume the characters are stored in an array called _characters    
         
          //Select a random index of the available characters  
          var selectedIndex = random.Next(0, _characters.Length);  
         
          //Get the selected character  
          var selectedCharacter = _characters[selectedIndex];  
       }  
    
    0 comments No comments