Quantcast
Viewing all articles
Browse latest Browse all 2703

Error on randomizing strings in a list C#

I want to create a program that shows a random category (from the list of category I've created) with the right words in a message box whenever I click the button.
Image may be NSFW.
Clik here to view.

The categories is randomized when I run it but the right word that should be with the category isn't correctly placed.
Image may be NSFW.
Clik here to view.

Also, I know that the program will crash once the program reaches a negative index of a category or once all of the category is shown.

Code:
namespace randomCategory
{
    public partial class Form1 : Form
    {

        Random rand = new Random();
        List<string> categories = new List<string> { "Book Titles", "Movie Titles", "Car Parts", "Human Body Parts", "Transportations" };

        public Form1()
        {
            InitializeComponent();
            listBox1.DataSource = categories;
        }

        public void selection()
        {
            // logic for setting a random category
            int index = rand.Next(categories.Count);
            var category = categories[index];
            
            
            // logic for assigning the word for a category
            switch (index)
            {
                case 0:
                    MessageBox.Show(category, "Harry Potter");
                    break;
                case 1:
                    MessageBox.Show(category, "Summer Wars");
                    break;
                case 2:
                    MessageBox.Show(category, "Bumper");
                    break;
                case 3:
                    MessageBox.Show(category, "Eyes");
                    break;
                case 4:
                    MessageBox.Show(category, "Boat");
                    break;
                default:
                    MessageBox.Show("Empty!", "!!!");
                    break;
            }

            categories.RemoveAt(index);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            selection();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}


Viewing all articles
Browse latest Browse all 2703

Trending Articles