read line by line from richtextbox and show in label (vb.net)

Olgu Kivanc picture Olgu Kivanc · Feb 6, 2016 · Viewed 11.7k times · Source

I would like to read line by line from richtextbox and show each line every a second in label.
I have this code blocks.
and I think I need a timer but I couldnt make it.
can you help me ?
Remarks :

If I use this code , I can only see the last line in label.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim RotateCount As String()
    For i As Integer = 0 To RichTextBox1.Lines.Length - 1
        Label1.Text = RichTextBox1.Lines(i)
    Next
End Sub

I mean, assume that we have lines in richtextbox like..

a1
b2
c3
d4
e5

and I would like to show label1 in for each second like..

a1 
(after 1 sec.)
b2 
(after 1 sec.)
c3 
(after 1 sec.)

like this...

Answer

Steve picture Steve · Feb 6, 2016

You seems to expect that, because you set the Text property, the label repaints itself immediately with the new text. This doesn't happen until you exit from the event handler and the system could repaint the label. Of course, with this code, only the last text is shown.

To reach your goal, you could use a Timer set to 1 second interval and a counter that keeps track of the current line dispayed:

 Dim tm As System.Windows.Forms.Timer = new System.Windows.Forms.Timer()
 Dim counter As Integer = 0

At this point your button click just start the timer and exits

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     tm.Interval = 1000
     AddHandler tm.Tick, AddressOf onTick
     tm.Start()
     ' Don't allow to click again this button until
     ' the timer is stopped
     Button1.Enabled = False
     Button2.Enabled = True
End Sub

When the Tick event is raised you change the label text to the line indexed by the counter, increment it and check if you have reached the last line restarting from the first one if this is the case. Note that the button is disabled before exiting. This is required to avoid a second/third/fourth/etc click on the same button while the timer runs..... More on Button2 later....

Sub onTick(sender as Object, e as EventArgs)
    Label1.Text = RichTextBox1.Lines(counter)
    counter += 1
    if counter >= RichTextBox1.Lines.Count Then
        counter = 0
    End If
End Sub

Of course, now you need another button to stop the Timer run and reenable the first button

' This button stops the timer and reenable the first button disabling
' itself - It should start as disabled from the form-designer
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    tm.Stop
    RemoveHandler tm.Tick, AddressOf onTick
    Button1.Enabled = True
    Button2.Enabled = False
End Sub