Rex Sixx
Rex Sixx

Reputation: 21

Getting random line from textfile on keypress [C#]

I'm trying to get a random line from a text file every time I press F9.

What I'm using is:

static class Randomyze
{
    public static string[] allLinks = File.ReadAllLines(@"links.txt");
    public static Random randomLink = new Random();
    public static int setLink = randomLink.Next(0, allLinks.Length - 1);
    public static String getLink = allLinks[setLink];
}

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.F9)
    { 
        MessageBox.Show(Randomyze.getLink); 
    }
        return true;
    else
    {
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

But I keep getting the same line when I press F9.

What am I doing wrong?

Upvotes: 0

Views: 39

Answers (2)

matt_t_gregg
matt_t_gregg

Reputation: 192

These two lines:

        public static int setLink = randomLink.Next(0, allLinks.Length - 1);
        public static String getLink = allLinks[setLink];

Execute only once when the class is initialized.

Your naming convention is actually pointing you to the way you want to go. Things with verbs (get, set, here) should usually correspond to functions. Try rewriting these as functions, returning items of interest (a link index, a link from the file).

Upvotes: 1

Code-Apprentice
Code-Apprentice

Reputation: 83527

Your code generates one random number when your program starts. You need to modify it so that you generate a new random number each time the key is pressed.

Hint: Do not use static at all.

Upvotes: 1

Related Questions