-1

I want to retrieve data from notepad and display it randomly on label. The project is about lucky draw system where i need to make the employee id display randomly.

Below are my code:

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        // Create an instance of StreamReader to read from a file.
        // The using statement also closes the StreamReader.
        using (StreamReader sr = new StreamReader("C:/ Users / Nor Asyraf Mohd No / Documents / TestFile.txt"))
        {
            string line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                string strRead = sr.ReadLine();
                Random random = new Random();
                Label1.Text = strRead.ToString();
            }
        }
    }
    catch (Exception i)
    {
        // Let the user know what went wrong.
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(i.Message);
    }
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
Ash93
  • 19
  • 4
  • 1
    a) format your code. b) don't declare [Random in a loop](https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number). c) You're probably best off loading all of them and choosing one at random afterwards. – ProgrammingLlama Mar 09 '18 at 00:50
  • 1
    [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – Robert Columbia Mar 09 '18 at 00:51
  • You need to first read all the number in a list of numbers. Then user random to generate random number between 0 and total items in the list and then user that random number to locate the item in the list. After the the number is displayed in the label, remove that item from the list so that the same number do not get selected again. – Chetan Mar 09 '18 at 00:59
  • Can you give me example in a code?thanks – Ash93 Mar 09 '18 at 01:12

1 Answers1

0

There are a couple of things wrong with your code. First, you should declare your Random variable once rather than inside a loop. Since Random uses the system time as a seed, if it's initialized inside a loop that's running quickly, you will likely get the same "random" number each iteration. I usually just declare it as a class field so it can be used by other methods as well.

Similarly, you can store the file path as a class level variable rather than each time the method is called. And if the file contents aren't changing, you should consider saving them in a List<string> class field one time at startup, rather than reading the file each time. But I'm going to assume that the file contents may change, so I'll leave that code in the method.

Next, you can use the File.ReadAllLines to get all the lines of the file at once, and then you can access a random index in the resulting string array of file lines.

In order to ensure you don't display the same item more than once, you can read the file lines once into a List<string>, and then, after you choose a random item from that list, remove it so it isn't used again.

For example:

private Random random = new Random();
private string testFilePath = @"c:\users\nor asyraf mohd no\documents\testfile.txt";
private List<string> testFileLines;

private void Form1_Load(object sender, EventArgs e)
{
    if (!File.Exists(testFilePath))
    {
        MessageBox.Show($"The file does not exist: {testFilePath}");
    }
    else
    {
        try
        {
            testFileLines = File.ReadAllLines(testFilePath).ToList();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Could not read file {testFilePath}. Exception details: {ex}");
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    if (testFileLines != null && testFileLines.Count > 0)
    {
        var randomLine = testFileLines[random.Next(testFileLines.Count)];
        Label1.Text = randomLine;
        testFileLines.Remove(randomLine);
    }
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • you did not fix exception handling code (if you going to fix all) :) (also I think question at most deserves to be duplicate of something... but it is not my effort) – Alexei Levenkov Mar 09 '18 at 01:21
  • Thanks a lot..it really work!! But how to make sure that the selected item do not get selected again? – Ash93 Mar 09 '18 at 01:24
  • @AlexeiLevenkov true, probably should have left it alone – Rufus L Mar 09 '18 at 01:25
  • @Ash93 You could remove the line from the file, or simply load the file once into a list during `Load`, and then remove the randomly selected item from that list in the Click event – Rufus L Mar 09 '18 at 01:27
  • @Ash93 I updated the sample to show how to cache the file contents into a local list, and then remove the random item each time. – Rufus L Mar 09 '18 at 01:37
  • @RufusL Thanks a lot,its really help. – Ash93 Mar 09 '18 at 02:27
  • @RufusL How can i select top 10 from notepad and display it on label? – Ash93 Mar 12 '18 at 03:18
  • What do you mean by *"top ten"*? You can sort the list by some criteria and then do `var topTen = sortedList.Take (10);` – Rufus L Mar 12 '18 at 04:07
  • I want to select just a few data like top ten from list on the notepad and display it randomly.Top 10 just an example. – Ash93 Mar 12 '18 at 06:10