Search code examples
c#winformsrandomgroupbox

Select and display a random group box each time a button is clicked


I am making a quiz game and one of my levels is going to be fill in the blanks. In this level I have laid out 10 different group boxes with a label and text boxes in each of them. I would like to be able to randomly select a different group box each time the next button is clicked. The next button will appear after the check button has been clicked to check the users answers in the text boxes and change the score variable. I need to ensure that the same group box doesn't show up twice.

private void frmLevel1_Load(object sender, EventArgs e)
    {
        groupBoxList.Clear();
        btnNext.Hide();
        this.BackgroundImage = gameClass.background;

        groupBoxList.Add(groupBox1);
        groupBoxList.Add(groupBox2);
        groupBoxList.Add(groupBox3);
        groupBoxList.Add(groupBox4);
        groupBoxList.Add(groupBox5);
        groupBoxList.Add(groupBox6);
        groupBoxList.Add(groupBox7);
        groupBoxList.Add(groupBox8);
        groupBoxList.Add(groupBox9);
        groupBoxList.Add(groupBox10);

        foreach (GroupBox box in groupBoxList) 
        {
            box.Hide();

        }

        Random groupBoxChooser = new Random(); }

Solution

  • You need Random.Next() to draw the lucky number:

    var luckyNumber = groupBoxChooser.Next(0,groupboxList.Count);
    

    If you want that to work from other methods as well, you should make the random number chooser a field instead of a local variable, so move this line out of the Form Load event into the class:

    Random groupBoxChooser = new Random();
    

    Then, you need the indexer to access an item of the list

    groupboxList[luckyNumber].Show();
    

    Since it does still not work for you, here's my full code:

    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    
    namespace GroupBoxRnd
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            IList<GroupBox> groupboxList = new List<GroupBox>();
            Random groupBoxChooser = new Random();
    
            private void Form1_Load(object sender, EventArgs e)
            {
                // Find all group boxes
                foreach (Control control in Controls)
                {
                    if (control.GetType() == typeof(GroupBox))
                        groupboxList.Add((GroupBox)control);
                }
    
                // Hide all of them
                foreach (GroupBox box in groupboxList)
                {
                    box.Hide();
                }
    
                // Show a random one
                var luckyNumber = groupBoxChooser.Next(0, groupboxList.Count);
                groupboxList[luckyNumber].Show();
            }
        }
    }