How to create a Lucky Draw games in C#

This post shows you How to implement 'Lucky Draw' functionality in C#

The lucky draw program uses random functions provided by c#. It allows you to create a set of winning numbers, the player will press the spin button, and the game will randomly select a number from the set as the winning number.

How to implement 'Lucky Draw' functionality in C#

Opening your Visual Studio, then create a new Windows Forms project

Next, You can design a simple UI allows you to generate numbers, then random number as shown below

lucky draw games in c#

Next, Create a list of string to store your number, _rand variable to random position, _count variable to count the spin time

List<string> _list;
Random _rand;
int _count;

Clicking on Create button, then add an event handler to generate number as shown below

private void btnGenerate_Click(object sender, EventArgs e)
{
    try
    {
        _count = 0;
        _list = new List<string>();
        _rand = new Random();
        int start = Convert.ToInt32(txtStartNumber.Text);
        int end = Convert.ToInt32(txtEndNumber.Text);
        for (int i = start; i <= end; i++)
            _list.Add(i.ToString());
        MessageBox.Show("The winning number set has been generated.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Just loop from start to end number, then add to list of string.

Finally, Click on the Lucky Draw button, then add an event handler that allows you to handle random numbers

//Lottery number generator in c#
private void btnLuckyDraw_Click(object sender, EventArgs e)
{
    try
    {
        if (_list == null)
        {
            MessageBox.Show("You have not created a set of bonus numbers.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        if (_list.Count > 0)
        {
            int pos = _rand.Next(0, _list.Count);
            lblResult.Text = _list[pos];
            _list.RemoveAt(pos);
            _count++;
            lblSpinTimes.Text = $"Spin times: {_count}";
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

We'll randomize the position from the list of strings, then display data according to the position value, and don't forget to delete the value at the random position