Data grid view updates hangs form

newbie14

New member
Joined
Jan 10, 2010
Messages
3
Programming Experience
1-3
Dear All,
I have an application where every minute it get updates from database and populate datagrid. So in the time of update the whole form and elements get hanged. So I have tried to now apply backgroundworker by dragging the backgroundworker component into my form together also with the progress bar component. The application is not running now and no error even in the immediate window. Below is my code. Any help please.
VB.NET:
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Public Class Grid

    Public strHTML
    
    Private Sub Grid_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        designGrid()

    End Sub

    Public Sub designGrid()
        dg1.AutoGenerateColumns = False
        dg1.Columns.Add("Date", "Date")
        dg1.Columns(0).Width = 120
        dg1.Columns(0).ReadOnly = True

        dg1.Columns.Add("Device ID", "Device ID")
        dg1.Columns(1).Width = 50
        dg1.Columns(1).ReadOnly = True

        dg1.Columns.Add("Violation Type", "Violation Type")
        dg1.Columns(2).Width = 100
        dg1.Columns(2).ReadOnly = True

        dg1.Columns.Add("Registration No.", "Regi No.")
        dg1.Columns(3).Width = 60
        dg1.Columns(3).ReadOnly = True

        dg1.Columns.Add("Contact No.", "C No.")
        dg1.Columns(4).Width = 70
        dg1.Columns(4).ReadOnly = True

        dg1.Columns.Add("Contact Person", "C Person")
        dg1.Columns(5).Width = 100
        dg1.Columns(5).ReadOnly = True

        dg1.Columns.Add("Fleet Name", "Name")
        dg1.Columns(6).Width = 120
        dg1.Columns(6).ReadOnly = True

        dg1.Columns.Add("Location", "Loc")
        dg1.Columns(7).Width = 250
        dg1.Columns(7).ReadOnly = True

        dg1.Columns.Add("Sim Card S.No", "Sim No")
        dg1.Columns(8).Width = 250
        dg1.Columns(8).ReadOnly = True

        dg1.Columns.Add("Trip ID", "ID")
        dg1.Columns(9).Width = 50
        dg1.Columns(9).ReadOnly = True


        'getData()
    End Sub

    Public Sub getData(ByVal worker As BackgroundWorker, ByVal e As DoWorkEventArgs)
        Dim strHTML As String

      
        Dim objWC As New System.Net.WebClient()
        strHTML = New System.Text.UTF8Encoding().GetString(objWC.DownloadData("http://localhost/test1/data5.php"))

        'MessageBox.Show("TEST : " + strHTML)
        Dim sites As Array
        Dim sites2 As Array
        Dim s As String
        sites = strHTML.Split("^")
        Dim j As Integer
        j = -1



        Try

            For Each s In sites
                j = j + 1
                'counter1 = counter1 + 1
                'Debug.Print(Trim(s))
                sites2 = s.Split("#")
                If (sites2.Length > 1) Then

                    Dim violationType As String
                    Dim violationCode As String
                    Dim violationString As String

                    Dim count As Integer


                    violationString = ""
                    violationString = Trim(sites2(11))
                    Dim strArr() As Char = violationString.ToCharArray()
                    Dim i As Integer
                    'MessageBox.Show("Original : " + Trim(sites2(11)))
                    violationCode = ""
                    violationString = ""
                    violationType = ""
                    For i = 0 To strArr.Length - 1

                        Dim modValue As Integer
                        modValue = i Mod 2
                        If modValue = 1 Then
                            violationCode = ""
                            violationCode = strArr(i - 1) + strArr(i)

                        End If


                    Next


                    dg1.Rows.Add(Trim(sites2(0)), Trim(sites2(3)), violationType, Trim(sites2(4)), Trim(sites2(8)), Trim(sites2(13)), Trim(sites2(2)), Trim(sites2(5)), Trim(sites2(12)), Trim(sites2(1)))
                    If (Trim(sites2(14)) <> "") Then
                        'MsgBox("TEST : " + j.ToString())
                        dg1.Rows(j).DefaultCellStyle.BackColor = Color.GreenYellow
                    End If
                    MessageBox.Show("LENGTH : " + sites.Length.ToString())
                    Dim percentComplete As Integer = CSng(j) / CSng(sites.Length) * 100
                    worker.ReportProgress(percentComplete)


                End If

            Next s


        Catch ex As Exception
            MessageBox.Show("cactch")

        Finally

        End Try

        'lblStatus.Text = "Completed"
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        dg1.Rows.Clear()
        'getData()
        Timer1.Stop()

        backgroundWorker1.RunWorkerAsync()


    End Sub
    Private Sub backgroundWorker1_DoWork( _
    ByVal sender As Object, _
    ByVal e As DoWorkEventArgs)


        If backgroundWorker1.IsBusy Then

        Else
            ' Get the BackgroundWorker object that raised this event.
            Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)


            ' Assign the result of the computation
            ' to the Result property of the DoWorkEventArgs
            ' object. This is will be available to the 
            ' RunWorkerCompleted eventhandler.

            getData(worker, e)


        End If

    End Sub 'backgroundWorker1_DoWork

    Private Sub backgroundWorker1_RunWorkerCompleted( _
    ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)


        ' First, handle the case where an exception was thrown.
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        ElseIf e.Cancelled Then
            ' Next, handle the case where the user canceled the 
            ' operation.
            ' Note that due to a race condition in 
            ' the DoWork event handler, the Cancelled
            ' flag may not have been set, even though
            ' CancelAsync was called.
            'resultLabel.Text = "Canceled"
        Else
            ' Finally, handle the case where the operation succeeded.
            'resultLabel.Text = e.Result.ToString()
        End If

        backgroundWorker1.Dispose()

        'Dim backgroundWorker1 As BackgroundWorker()
        Timer1.Start()


    End Sub 'backgroundWorker1_RunWorkerCompleted

    Private Sub backgroundWorker1_ProgressChanged( _
    ByVal sender As Object, ByVal e As ProgressChangedEventArgs)


        Me.progressBar1.Value = e.ProgressPercentage


    End Sub
    
    
End Class
 
Dear All,
I have done some changes to my codes now. What I did I remove the backgroundWorker1 component from the form and replace it with this line of the code "Private WithEvents backgroundWorker1 As New BackgroundWorker()". Then I ran my application and got this error "Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on. So ok I then commented both this lines in my code
VB.NET:
dg1.Rows.Add(Trim(sites2(0)), Trim(sites2(3)), violationType, Trim(sites2(4)), Trim(sites2(8)), Trim(sites2(13)), Trim(sites2(2)), Trim(sites2(5)), Trim(sites2(12)), Trim(sites2(1)))

dg1.Rows(j).DefaultCellStyle.BackColor = Color.GreenYellow
. Then I ran again and got this error " The BackgroundWorker states that it doesnt report progress. Modify WorkerReportProgress to state it does report progress" which I am totall loss because I already have report progress function. Any help please. Below is my updated codes.
VB.NET:
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Public Class Grid

    Public strHTML

    Private WithEvents backgroundWorker1 As New BackgroundWorker()
    Private Sub Grid_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        designGrid()

    End Sub

    Public Sub designGrid()
dg1.AutoGenerateColumns = False
dg1.Columns.Add("Date", "Date")
dg1.Columns(0).Width = 120
dg1.Columns(0).ReadOnly = True

dg1.Columns.Add("Device ID", "Device ID")
dg1.Columns(1).Width = 50
dg1.Columns(1).ReadOnly = True

dg1.Columns.Add("Violation Type", "Violation Type")
dg1.Columns(2).Width = 100
dg1.Columns(2).ReadOnly = True

dg1.Columns.Add("Registration No.", "Regi No.")
dg1.Columns(3).Width = 60
dg1.Columns(3).ReadOnly = True

dg1.Columns.Add("Contact No.", "C No.")
dg1.Columns(4).Width = 70
dg1.Columns(4).ReadOnly = True

dg1.Columns.Add("Contact Person", "C Person")
dg1.Columns(5).Width = 100
dg1.Columns(5).ReadOnly = True

dg1.Columns.Add("Fleet Name", "Name")
dg1.Columns(6).Width = 120
dg1.Columns(6).ReadOnly = True

dg1.Columns.Add("Location", "Loc")
dg1.Columns(7).Width = 250
dg1.Columns(7).ReadOnly = True

dg1.Columns.Add("Sim Card S.No", "Sim No")
dg1.Columns(8).Width = 250
dg1.Columns(8).ReadOnly = True

dg1.Columns.Add("Trip ID", "ID")
dg1.Columns(9).Width = 50
dg1.Columns(9).ReadOnly = True


    End Sub

    Public Sub getData(ByVal worker As BackgroundWorker, ByVal e As DoWorkEventArgs)
        Dim strHTML As String

      
        Dim objWC As New System.Net.WebClient()
        strHTML = New System.Text.UTF8Encoding().GetString(objWC.DownloadData("http://localhost/test1/data5.php"))

        'MessageBox.Show("TEST : " + strHTML)
        Dim sites As Array
        Dim sites2 As Array
        Dim s As String
        sites = strHTML.Split("^")
        Dim j As Integer
        j = -1



        Try

            For Each s In sites
                j = j + 1
                'counter1 = counter1 + 1
                'Debug.Print(Trim(s))
                sites2 = s.Split("#")
                If (sites2.Length > 1) Then

                    Dim violationType As String
                    Dim violationCode As String
                    Dim violationString As String

                    Dim count As Integer


                    violationString = ""
                    violationString = Trim(sites2(11))
                    Dim strArr() As Char = violationString.ToCharArray()
                    Dim i As Integer
                    MessageBox.Show("Original : " + Trim(sites2(11)))
                    violationCode = ""
                    violationString = ""
                    violationType = ""
                    For i = 0 To strArr.Length - 1

                        Dim modValue As Integer
                        modValue = i Mod 2
                        If modValue = 1 Then
                            violationCode = ""
                            violationCode = strArr(i - 1) + strArr(i)

                        End If


                    Next


                    'dg1.Rows.Add(Trim(sites2(0)), Trim(sites2(3)), violationType, Trim(sites2(4)), Trim(sites2(8)), Trim(sites2(13)), Trim(sites2(2)), Trim(sites2(5)), Trim(sites2(12)), Trim(sites2(1)))
                    If (Trim(sites2(14)) <> "") Then
                        'MsgBox("TEST : " + j.ToString())
                        'dg1.Rows(j).DefaultCellStyle.BackColor = Color.GreenYellow
                    End If
                    MessageBox.Show("LENGTH : " + sites.Length.ToString())
                    Dim percentComplete As Integer = CSng(j) / CSng(sites.Length) * 100
                    worker.ReportProgress(percentComplete)


                End If

            Next s


        Catch ex As Exception
            MessageBox.Show("cactch"+ex.Message)

        Finally

        End Try

        'lblStatus.Text = "Completed"
    End Sub


    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        dg1.Rows.Clear()
        'getData()
        Timer1.Stop()

        MessageBox.Show("TEST")
        MessageBox.Show("DO WORK" + backgroundWorker1.IsBusy.ToString())
        If backgroundWorker1.IsBusy Then
        Else
            backgroundWorker1.RunWorkerAsync()
        End If

    End Sub
    
     'backgroundWorker1_RunWorkerCompleted

   
    Public Function GetPageHTML( _
          ByVal URL As String) As String
        ' Retrieves the HTML from the specified URL
        Dim objWC As New System.Net.WebClient()
        Return New System.Text.UTF8Encoding().GetString( _
           objWC.DownloadData(URL))
    End Function



    Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles backgroundWorker1.DoWork


       
        ' Get the BackgroundWorker object that raised this event.
        'Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)


        getData(backgroundWorker1, e)



    End Sub

    Private Sub backgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles backgroundWorker1.ProgressChanged
        Me.ProgressBar1.Value = e.ProgressPercentage
    End Sub

    Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles backgroundWorker1.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        ElseIf e.Cancelled Then
            ' Next, handle the case where the user canceled the 
            ' operation.
            ' Note that due to a race condition in 
            ' the DoWork event handler, the Cancelled
            ' flag may not have been set, even though
            ' CancelAsync was called.
            'resultLabel.Text = "Canceled"
        Else
            ' Finally, handle the case where the operation succeeded.
            'resultLabel.Text = e.Result.ToString()
        End If

        'backgroundWorker1.Dispose()

        'Dim backgroundWorker1 As BackgroundWorker()
        Timer1.Start()
    End Sub
End Class
 
Dear All,
Ok I managed to solve the error "The BackgroundWorker states that it doesnt report progress. Modify WorkerReportProgress to state it does report progress" by inserting this line backgroundWorker1.WorkerReportsProgress = True into Grid_Load function. So my next problem is how can I update my datagrid as it is giving Cross Thread error. Thank you.
 
Back
Top