I need to randomly run a method that will read a string from a text file and display it with a TextBox until the lines in the file run out. It turned out that's what.
Random rand = new Random(); Timer mytimer = new Timer(); public void Timer() { mytimer.Tick += new EventHandler(Reader); mytimer.Interval = rand.Next(1000, 3000); mytimer.Enabled = true; mytimer.Start(); } public int TotalLines() { using (StreamReader r = new StreamReader(@"test.txt")) { int i = 0; while (r.ReadLine() != null) { i++; } return i; } } public void Reader(Object myObject, EventArgs myEventArgs) { StreamReader file = new StreamReader(@"test.txt"); progressBar1.Maximum = TotalLines(); for (int i = 0; i <= TotalLines(); i++) { textBox1.Text = file.ReadLine(); progressBar1.Value = i; } file.Close(); mytimer.Interval = rand.Next(1000, 3000); } private void button1_Click(object sender, EventArgs e) { Timer(); }
But with this problem code, firstly, the string in the textbox is not drawn, and in the second, the timer chases this method in a circle. Where am I wrong?
I figured out the timer as follows
public void Reader(Object myObject, EventArgs myEventArgs) { StreamReader file = new StreamReader(@"test.txt"); int f = TotalLines(); progressBar1.Maximum = f; for (int i = 0; i <= f; i++) { textBox1.Text = file.ReadLine(); progressBar1.Value = i; mytimer.Interval = rand.Next(1000, 3000); mytimer.Stop(); } file.Close(); }