Home > other >  Displaying a random number in a label
Displaying a random number in a label

Time:04-13

I am trying to display a random number in a label I created, but I have a syntax error. Is there a way I can do this and show it in a label instead of Console.Write?

public partial class frmNumber : Form
{
    public frmNumber()
    {
        InitializeComponent();
    }

    public int RandomNumber()
    {
        int num; 
        Random random = new Random();
        num = random.Next(100);

        lblRandom.Text = num.ToString();
    }
    return num;
  // I have an error under return num;    
}

}

CodePudding user response:

You need to correct your method and you need to call it after InitializeComponent, otherwise, it is never called.

public frmNumber()
{
    InitializeComponent();
    RandomNumber();
}

public void RandomNumber()
{
    Random random = new Random();
    var num = random.Next(100);

    lblRandom.Text = num.ToString();
}

If you need also to return the number you can do it this way:

public frmNumber()
{
    InitializeComponent();
    lblRandom.Text = RandomNumber().ToString();
}

public int RandomNumber()
{
    Random random = new Random();
    var num = random.Next(100);
    return num;
}
  • Related