Random Number Generator In C#

random number generator in c#

This tutorial will teach you on how to build a program that generates a random number using C#.

Let’s start making this program!

1. Create a Windows Form Application in C# for this tutorial by following the following steps in Microsoft Visual Studio 2019: Go to File, click New, and choose Windows Form Application and name your project as Random Number Generator.

2. Add one button and named Button1. Have it also labeled as “Create Random Number“. Follow this designed interface:


3. Then, in the code tab, create a code for your Button1_Click. Type this code below:

public Random random = new Random();
public void Button1_Click(System.Object sender, System.EventArgs e)
    int i = default(int);
    for (i = 1; i <= 3; i++)
        MessageBox.Show(Convert.ToString(random.Next(0, 1000)));

We declare public Random random = new Random(); as our Global Variable for instantiating a Random Object new Random(); that holds the variable random. We also initialized Dim i As Integer as our integer so that we can generate three random numbers (For i=1 to 3) when we click OK button in the MsgBox.

MessageBox.Show(Convert.ToString(random.Next(0, 1000))); the syntax is for displaying the random number. random.Next(0, 1000) initializes a random number from 0 to 1000, then the output is converted into a string using Convert.ToString syntax.

Click your Button. It will now generate a random number like this:


Click OK button in the MessageBox again. It will generate again a random number like this:


Lastly, click the OK button. It will generate again a random number like this:


The program can only generate random numbers three times as we conditioned For i = 1 to 3.

Click the Download Code Button below to download source code.

Download Code

Sharing is caring!

Facebook Comments

Leave a Reply