Pause a "FOR EACH" routine

VS2005, VB.Net
Hello experts,

I have a form with various labels. My app runs through a datatable row by row and updates the labels wtih values in each row. I need to pause after each update for about 5 seconds, then conitnue with the next update, pause 5 secs, etc, etc.

For Each row In table.Rows
      lbl1.text = "this"
      lbl2.text = "that"

' need to add pause here for 5 seconds

I have tried a timer but it runs through every all of teh rows really quickly, regardsless of how long the timer is set.


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.


The number is milliseconds.
Jorge PaulinoIT Pro/DeveloperCommented:
The solution of rhythmluvr should work but you also should add Application.DoEvents() to doesn't lock the app.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Use a BackgroundWorker and place your code in the DoWork event.  Add a Sleep(5000) statement where you want the pause.  Don't use Sleep on the UI thread.
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

webkiwi1Author Commented:
If I understand correctly using the System.Threading.Thread.Sleep command pauses ALL of the code. I have a seperate feature running that crawls text across the screen and I need that to continue. The System.Threading.Thread.Sleep(200) works but locks up my text crawl...
webkiwi1Author Commented:
In regards to the crawl I have running, it is a seperate windows form that is overlaid in front of the main form if that makes a difference!
That's why you need to use the BackgroundWorker!
webkiwi1Author Commented:
ok, BackgroundWorker sounds like a direction I can go in. I looked as the MSDN site and it is way over my head!!! Is that the only way?

I just discovered that the crawl is also using a timer...
The BackgroundWorker component is supposed to simplify threading.  You can spawn your own threads if you find it easier.  You can also do what you want to do using a timer, but the for each with a sleep statement is probably easier to understand.
Jorge PaulinoIT Pro/DeveloperCommented:
Hi webkiwi1,

Using a BackgroundWorker  is a easy way of handling threads but you cannot populate another control only using that. You must use delegates. You start a new thread, then the thread call a delegate that allow you to call safelly your update method. You can do this using BackgroundWorker  or codding everything. I will show you an example how to do it creating a new thread.

Hope this helps.
Imports System.Threading
Public Class Test
    Delegate Sub dgvDelegate()
    ' Call the delegate
    Private Sub dgvThreadMain()
        If Me.InvokeRequired Then
            Me.Invoke(New dgvDelegate(AddressOf UpdateDGV))
        End If
    End Sub
    ' Update DataGridView Code
    Private Sub UpdateDGV()
        ' update code of the DataGridView 
    End Sub
' Form Load Event
Private Sub frmForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim dgvThread As New Threading.Thread(AddressOf dgvThreadMain)
            dgvThread.Priority = ThreadPriority.Highest
            dgvThread.IsBackground = True
End Sub
End Class

Open in new window

webkiwi1Author Commented:
OK, this is a little over my head but the thought process has been started...
I think the best solution is to add the "ticker" or text crawl to a seperate thread. The Ticker is a new windows form that is overlaid on the main form that contains the sleep command. Here is the entire code for the ticker windows form and how it is called from frmDisplay. I am not using the parts that are commented out...

How would I use the example provided by jpaulino for this form without getting the "cross thread" exception?
In the frmDisplay_load event:
Private Sub frmDisplay_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'frmTicker.Location = New Point(0, 400)
Me.WindowState = FormWindowState.Normal
Dim f As New frmTicker
            With f
                frmTicker.Location = Me.PointToScreen(New Point(CheckBox1.Left, CheckBox1.Top + CheckBox1.Height))
            End With
   End Try
End Sub
which calls this:
Imports System.Text    'used for string manipulations
Imports System.Xml     ' used for XML reading
Public Class frmTicker
    Inherits System.Windows.Forms.Form
    Dim widthX As Single
    Dim heightY As Single = 10
    Dim g As Graphics
    Dim xmlst As String      'string from the xml file
    Dim fo As Font
    Dim str As String
    Dim strwidth As SizeF    'gets the xml string's width and height 
    Dim douX As Double       'stores the xmlstring's width 
    Private Sub NewsTicker_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        g = Me.CreateGraphics()  'get the graphics object of the form
        widthX = Me.Width        ' x co- ordinate or width
        ' Debug.Write(String.Format("The width is {0}", CStr(Me.Width)))
        If frmMain.rbpredis.Checked = True Then
            str = "Message 1" 
        End If
        If frmMain.rbPostDis.Checked = True Then
            str = "Message 2" 
        End If
        Dim gr As Graphics
        Timer1.Interval = 100
        fo = New Font("Arial", 14, FontStyle.Bold, GraphicsUnit.Point)
        strwidth = g.MeasureString(str, fo)
        douX = strwidth.Width
    End Sub
    'Private Sub loadthenews()
    '    Dim readXML As New XmlTextReader("c:\temp\ticker\ticker.xml")
    '    While readXML.Read()
    '        If readXML.NodeType = XmlNodeType.Text Then
    '            str += "  Hello " & readXML.Value
    '        End If
    '    End While
    'End Sub
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        'Debug.Write(vbCr & strwidth.Width & vbCr)
        'Debug.Write(String.Format("widthX = {0}", CStr(widthX) & vbCr))
        g.DrawString(str, fo, Brushes.White, widthX, heightY)
        ' Debug.Write(String.Format("the string width is {0}", CStr(strwidth.Width)))
        If widthX <= (0 - douX) Then
            widthX = Me.Width
            widthX -= 5
        End If
    End Sub
    'Private Sub NewsTicker_hover(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.MouseHover
    '    Timer1.Stop()
    '    Debug.Write(String.Format("The string width is {0}", CStr(douX)))
    'End Sub
    'Private Sub NewsTicker_leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.MouseLeave
    '    Timer1.Start()
    'End Sub
End Class

Open in new window

Jorge PaulinoIT Pro/DeveloperCommented:
>> My app runs through a datatable row by row and updates the labels wtih values in each row. I need to pause after each update for about 5 seconds, then conitnue with the next update, pause 5 secs, etc, etc.


In you first question you have asked for help with update row/labels using a pause for 5 seconds but in your code I don't see that. Can you show us the right code or show us a demo of your project ( I can show you how to use threads but I don't see the need in the above code.

>> without getting the "cross thread" exception

Have you tried already something ?
webkiwi1Author Commented:
Project got scrapped before I could work out the background writer...thanks for the suggestions.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.