Search code examples
c#numericupdown

numericUpDown used with return values


I am pretty new to c#, I am taking a class and we didn't cover numericUpDown at all. I am creating a basic dice roller for a project and have the basics laid out, however I can't seem to figure out how to add the numericUpDown how I would like.

private void btn4_Click(object sender, EventArgs e)
        {
            Random rnd = new Random();
            int randomnumber = rnd.Next(1, 5); //+1 higher than the dice selected
            txt4.Text = randomnumber.ToString();
        }

Image of a piece of the GUI

I want to be able to use the numericUpDown to select the amount of dice rolled and then when you click roll it will return however many values the numericUpDown has indicated. For example: If you have 4 selected on the numericUpDown it will return 4 random numbers when you click roll.


Solution

  • You'll need to use the value of your NumericUpDown in a for loop to tell it how many times to roll

    Example:

    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Clear() // Empty the text box before rolling
        Random rnd = new Random();
    
        for (int i = 0; i < numericUpDown1.Value; i++)
        {
            int randomNumber = rnd.Next(1, 5);
            textBox1.AppendText($"Roll {i + 1}: {randomNumber}\r\n");
        }
    
    }