Rixcy
Rixcy

Reputation: 284

Choose a random variable from a list on button press in c#

I'm making a Windows Forms Application where I want to be able to show a messagebox with a random variable from a list on button press. I made a class called SetRandomCode which sets up the list and hopefully sets a random number to the variable 'testVariable.' I'm fairly new to c# so I may be going about this the completely wrong way but here's my code:

SetRandomCode.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication2
{
    public class SetRandomCode
    {
        List<string> randomCodes = new List<string>();

        public void setCode()
        {
            Random r = new Random();
            int index = r.Next(randomCodes.Count);
            string testVariable = randomCodes[index];
            randomCodes.Add("Test");
            randomCodes.Add("Test 2");
            randomCodes.Add("Test 3");
        }
    }
}

Form1.cs

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(testVariable);
        }
    }
}

The error I'm getting is 'the name 'testVariable' does not exist in the current context.

Any help with this would be greatly appreciated :)

Upvotes: 0

Views: 503

Answers (1)

Alfie Goodacre
Alfie Goodacre

Reputation: 2793

Try making the class in SetRandomCode static

public static class SetRandomCode
{

    public static string setCode()
    {
        List<string> randomCodes = new List<string>();
        randomCodes.Add("Test");
        randomCodes.Add("Test 2");
        randomCodes.Add("Test 3");
        Random r = new Random();
        int index = r.Next(0, randomCodes.Count);
        return randomCodes[index];
    }
}

and then in form1

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

    private void button1_Click(object sender, EventArgs e)
    {
        string testVariable = SetRandomCode.setCode();
        MessageBox.Show(testVariable);
    }
}

A few other differences in the code is that the list is populated before you count it, otherwise the returned value will always be 0, the list is also populated before you get a value from it to avoid errors.

In this new code, test variable is being set in Form1 instead of in your entirely separate class. By being static, the class can have its methods called without being instantiated, allowing for the closest thing to what you were trying before

Upvotes: 3

Related Questions