0

I want to read single line and put it into textbox every 1 second. I managed this code:

private void button1_Click(object sender, EventArgs e)
{
    while ((line = file.ReadLine()) != null)
    {
        timer.Start();
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    textBox1.text += line + "\r\n";
}

But the line is not accessable. I also tried something like this:

private void button1_Click(object sender, EventArgs e)
{
    timer.Start();
}


private void timer1_Tick(object sender, EventArgs e)
{

    while ((line = file.ReadLine()) != null)
    {
        textBox1.Text += line + "\r\n";
    }

}

But it's ignoring the timer interval. What's more I have no idea how can I stop the timer in both examples. Can you give me a tip what could I do with this?

Edit

Any ideas why this code works good with if but not with while?

 private void timer1_Tick(object sender, EventArgs e)
        {

            while ((line1 = file1.ReadLine()) != null)
            {


                while ((line2 = file2.ReadLine()) != null)
                {

                    try
                    {
                            //some code
                    }

                    catch
                    {

                            //some code
                    }

                    finally
                    {
                            //some code

                    }

                }
               


            }
          
                timer1.Stop();
            

        }

I want to combine every row from file2 with every row from file1.

Community
  • 1
  • 1
audiophonic
  • 171
  • 1
  • 13
  • First example will do strange things, Second example is very unclear since we dont know, how your timer is initialized – lokusking Jul 22 '16 at 22:09
  • 1
    Hint: Make it global and in timer1_Tick(), read next line, display it and reStart your timer. – Khalil Khalaf Jul 22 '16 at 22:11
  • The first block of code says "for each line in the file, start the timer". I think this might be one part of your problem. If you put `timer.Start` after the while block then you might get a little further. I also don't know what you mean by "But the `line` is not accessible". Do you mean that you don't see the text in the text box, but you are expecting to? You also aren't adding any of those lines into the text field inside that loop, so the whole file (except for the last "line", which will be null) is getting read and discarded before anything else happens. – Merlyn Morgan-Graham Jul 22 '16 at 22:11
  • 1
    _"I have no idea how can I **stop** the timer in both examples"_ - hmmm. If only there was a `Stop()` method? –  Jul 22 '16 at 22:12
  • How can I restart my timer? – audiophonic Jul 22 '16 at 22:19
  • @audiophonic Just call `.Star()` every time. – Khalil Khalaf Jul 22 '16 at 23:06
  • 1
    Don't **edit** your old question to include a _new different question_. Instead **post a new question** –  Jul 22 '16 at 23:30

4 Answers4

1

This code will take a line from a given file (currently c:\myfile\test.xml) and read it into an array, then start the timer. Once the timer has been started it will determine if the end of your data has been met. If there is still data left then you will have it appended into the textbox. If no data is left the timer will stop. You can press the button again to restart the process again.

    //holds each line of the file contents
    string[] lines = null;
    //sets the current line number that you are at in the lines array
    int curline = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //reads all lines of files and starts the timer
        lines = File.ReadAllLines(@"C:\myfile\test.xml");
        curline = 0;
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        //if not end of data then insert on another line of the textbox
        if (curline < lines.Length)
        {
            textBox1.Text += lines[curline] + "\r\n";
            curline++;
        }
        else
        {
            //else stop the timer
            timer1.Stop();
        }
    }

Happy Coding, Jason

  • +1 for correct scoping of variables. I'd suggest using a Queue for lines, and not a string array, and pulling the line each time on timer1_Tick with lines.Dequeue(), rather than a curline field. Your approach is perfectly workable, though. – Wesley Long Jul 22 '16 at 22:56
  • @audiophonic You should post that as a new question –  Jul 22 '16 at 23:30
1

In the second example change the code to following

private void timer1_Tick(object sender, EventArgs e) {
   if((line = file.ReadLine()) != null) 
   { textBox1.Text += line + "\r\n"; 
   } 
   else
   {
    //Stop Timer here
   }
}
Paresh
  • 993
  • 1
  • 7
  • 15
  • 1
    The only issue is that you've left the 'file' object's lock on the file open after you're done processing it. Probably more than this exercise is concerned about, though. – Wesley Long Jul 22 '16 at 23:01
0

My best option: (assumes myFilePath contains the path to the file you're using)

       private Queue<string> _lines;

    private void button1_Click(object sender, EventArgs e)
    {
        _lines = new Queue<string>(System.IO.File.ReadAllLines(myFilePath));
        textBox1.Text = string.Empty;
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (_lines.Any())
            textBox1.Text += _lines.Dequeue() + Environment.NewLine;
        else
            timer1.Stop();
    }
Wesley Long
  • 1,708
  • 10
  • 20
0

Here is the Solution:

As mentioned in the comments, start everything at the beginning and in the background. First read your file and prepare a container of your lines. Then, start a timer. Now every time the timer1.Ticks, we will display a line from our container starting from the first line. We keep doing the process again and again.

Watch out for your file path.

MyFile: "C:\Users\Public\TestFolder\Test.txt"

a

b

c

d

e

f

Code ready to compile:

using System;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class ExampleProgram : Form
    {
        // global variables  
        string[] MyLines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\Test.txt"); // contain all lines
        int MyCurrentLine = 0;

        public ExampleProgram()
        {
            InitializeComponent();
            StartProgram(); // start the program
        }

        private void StartProgram()
        {
            timer1.Interval = 1000; // set interval in milliseconds
            timer1.Start(); // start timer
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //timer1.Stop(); // first thing first - Edit: Looks like you did not need this.
            textBox1.Text = MyLines[MyCurrentLine % MyLines.Count()]; // display next line
            ++MyCurrentLine; // increment counter
            //timer1.Start(); // restart - Edit: And also won't need this. Less code.. Nice !
        }
    }
}

Result:

enter image description here

Community
  • 1
  • 1
Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104
  • Why stop/start the timer in `timer1_Tick`? It's not as if the callback takes a long time –  Jul 22 '16 at 23:33
  • @MickyD I am not sure, but the professor who taught me this told me to do so. Maybe I should remove it then :) Thanks for pointing that out – Khalil Khalaf Jul 22 '16 at 23:35
  • All's good. Nice animation too by the way, more SO answers should do this :) –  Jul 23 '16 at 01:58
  • Now you got me wondering why it was recommended back then @MickyD Thank you :) – Khalil Khalaf Jul 23 '16 at 02:03
  • 1
    All I can think of is some [readability issue](http://stackoverflow.com/a/1013320/585968). I agree start/stop in a method is more readable but if you understand timers, then restarting is not required in this respect. :) –  Jul 23 '16 at 02:09
  • 1
    Nah I am a noob when it comes to timers ;) Thanks for referring your point – Khalil Khalaf Jul 23 '16 at 02:13
  • 1
    hehe, no worries :D –  Jul 23 '16 at 02:17