locked
How to roll a list of numbers (list of numbers are in a notepad ) randomly in a lable RRS feed

  • Question

  • User1933868974 posted

    Hi,

    I want to retrieve data from notepad and display it randomly on lable. The project is about lucky draw system where i need to make the employee id display randomly. Can someone help me out with the problem. Below are my code. Thanks

    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);
    }
    }
    }

    Thursday, March 8, 2018 6:08 AM

All replies

  • User-1838255255 posted

    Hi Ash93,

    According to your description, i think this issue is belong to winform project, here is asp.net forum, please check the following code: 

    Sample Code: 

    private void button1_Click(object sender, EventArgs e)
            {
                string fileName = @"D:\McTextFile.txt";
    
                int count = TotalLines(fileName);
                int[] necount = new int[count];
                int i = 0;
                using (StreamReader r = new StreamReader(fileName))
                {
                    String input;
                    while ((input = r.ReadLine()) != null)
                    {
                        necount[i] = Convert.ToInt32(input);
                        i++;
                    }
                }
    
                Random random = new Random();
                int start2 = random.Next(0, necount.Length);
                textBox1.Text = necount[start2].ToString();
            }
    
            public int TotalLines(string filePath)
            {
                using (StreamReader r = new StreamReader(filePath))
                {
                    int i = 0;
                    while (r.ReadLine() != null) { i++; }
                    return i;
                }
            }
    
    txt file:
    12
    20 
    48 
    25 
    90 
    89

    Best Regards,

    Eric Du 

    Friday, March 9, 2018 10:11 AM