Question Loading DataGridView in Thread (several issues)

Status
Not open for further replies.

rvercesi

Member
Joined
Oct 16, 2008
Messages
10
Programming Experience
5-10
Hi guys
Still around importing Excel Files to DataGridView.
Since my main problem was to keep color formating, I got to use the following function:

VB.NET:
Private Sub LoadXLSFile()
        Dim xlApp As New Microsoft.Office.Interop.Excel.Application
        System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
        Dim xlWB As Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Open(lblSelectedXLSFile.Text)
        Dim xlWS As Microsoft.Office.Interop.Excel.Worksheet = xlWB.Worksheets("Sheet1")

        dgvXLS.RowCount = xlWS.UsedRange.Rows.Count - 1
        dgvXLS.ColumnCount = xlWS.UsedRange.Columns.Count

        Try
            For c As Integer = 1 To xlWS.UsedRange.Columns.Count
                dgvXLS.Columns(c - 1).HeaderText = xlWS.UsedRange.Cells(1, c).Value
            Next
            For r As Integer = 2 To xlWS.UsedRange.Rows.Count
                For c As Integer = 1 To xlWS.UsedRange.Columns.Count
                    With dgvXLS(c - 1, r - 2)
                        .Value = xlWS.UsedRange.Cells(r, c).Value
                        .Style.BackColor = ColorTranslator.FromOle(xlWS.UsedRange.Cells(r, c).Interior.Color)
                    End With
                Next
                'progressBar1.Value = r * 100 / (xlWS.UsedRange.Rows.Count - 2)

            Next
            MsgBox("XLS LOADED SUCCESSFULY", MsgBoxStyle.Information)
        Catch ex As Exception
            MsgBox("ERROR LOADING XLS: " & vbCrLf & ex.Message, MsgBoxStyle.Critical)
        Finally
            xlWS = Nothing
            xlWB.Close(False)
            xlWB = Nothing
            xlApp.Quit()
            xlApp = Nothing
        End Try

    End Sub

I got around several issues regarding localization and excel versions. But now I am stuck in trying to put this SUB in a Thread. No so much by putting this AS IT IS but because I want to pass several arguments to filter the XLS before loading it to the DataGridView.

I can get it to work (but doesn't seems multithreading as it freezes my app) using:

VB.NET:
    Delegate Sub dgvDelegate()

    Private Sub dgvThreadMain()
        If Me.InvokeRequired Then
            Me.Invoke(New dgvDelegate(AddressOf LoadXLSFile))
        End If
    End Sub

And calling it like this:

VB.NET:
Dim dgvThread As New Threading.Thread(AddressOf dgvThreadMain)
dgvThread.Priority = ThreadPriority.Normal
dgvThread.IsBackground = True
dgvThread.Start()

But again, as I mentioned before, it freezes my app while loading the XLS on to the DataGridView (therefore shadowing the purpose of using threads) and I can not get it to work when I pass arguments to the SUB.

Need help urgently on this one. Than you.
 
Status
Not open for further replies.
Back
Top