1

I am currently working on an indexing program. I recently added during my Regex searched through files a way to detect duplicates of the Regex inside the same file.

The problem is I get:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.

When I call my export function which would write the duplicates to a file. However I use the export functions many times in other parts of the program and I have never encountered this problem before.

To put short what I do is:

  1. FormStats.vb:

    1.1. Regex Search through BackGroundWorker()

    1.2. Store Duplicates if any

    1.3. Call on BackGroundWorker_RunWorkerCompleted to ExportDoublon()

  2. FileHandler.vb

    2.1. Call on WriteDoublon() To exportToWord()

  3. Exporter.vb

    3.1. exportToWord()

Line where the error appears:

Clipboard.SetText(table) 

The way the class is called from FileHandler.vb:

Public Sub WriteDoublon(ByVal CurrentDoub As List(Of Doublon))
    Dim dgv As New DataGridView
    dgv.Columns.Add("Name", "Name")
    dgv.Columns.Add("Fiche", "Fiche")
    For Each doublee As Doublon In CurrentDoub
        dgv.Rows.Add(doublee.Name, doublee.Ficher)
        dgv.Rows.Add("**********", "**********")
    Next
    Dim exp As New Exporter
    Dim prog As New ProgressBar
    exp.exportToWord(dgv, AppDomain.CurrentDomain.BaseDirectory & "Exports\Doublon.docx", prog)
End Sub

The place where FileHandler.WriteDoublon() is called FormStats.vb:

Public Sub ExportDoublon()
    Dim fl As New FileHandler
    fl.WriteDoublon(Doub)
End Sub

Class where the error appears Exporter.vb:

Public Sub exportToWord(ByVal dgv As DataGridView, ByVal pather As String, ByVal progresser As ProgressBar)    
    Dim oWord As Word.Application = DirectCast(CreateObject("Word.Application"), Word.Application)
    Dim oDoc As Word.Document = oWord.Documents.Add()
    oWord.Visible = False    
    Dim headers = (From ch In dgv.Columns
                   Let header = DirectCast(DirectCast(ch, DataGridViewColumn).HeaderCell, DataGridViewColumnHeaderCell)
                   Select header.Value).ToArray()
    Dim headerText() As String = Array.ConvertAll(headers, Function(v) v.ToString)

    Dim items() = (From r In dgv.Rows
                   Let row = DirectCast(r, DataGridViewRow)
                   Where Not row.IsNewRow
                   Select (From cell In row.Cells
                           Let c = DirectCast(cell, DataGridViewCell)
                           Select c.Value).ToArray()).ToArray()    
    Dim table As String = String.Join(vbTab, headerText) & Environment.NewLine
    Dim i As Integer = 0
    For Each a In items
        Dim t() As String = Array.ConvertAll(a, Function(v) v.ToString)
        table &= String.Join(vbTab, t) & Environment.NewLine
        progresser.Value = i * 100 / items.Count
        i = i + 1
    Next
    table = table.TrimEnd(CChar(Environment.NewLine))
    '--ERROR HERE
    Clipboard.SetText(table)
    '#############    
    Dim oTable As Word.Table = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, items.Count + 1, headers.Count)    
    oTable.Range.Paste()    
    'make the first row bold, fs 14 + change textcolor
    oTable.Rows.Item(1).Range.Font.Bold = &H98967E
    oTable.Rows.Item(1).Range.Font.Size = 14
    oTable.Rows.Item(1).Range.Font.Color = Word.WdColor.wdColorWhite    
    'change backcolor of first row
    oTable.Rows.Item(1).Range.Shading.Texture = Word.WdTextureIndex.wdTextureNone
    oTable.Rows.Item(1).Alignment = Word.WdAlignmentTabAlignment.wdCenter
    oTable.Rows.Item(1).Range.Shading.ForegroundPatternColor = Word.WdColor.wdColorAutomatic
    oTable.Rows.Item(1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorPaleBlue    
    'set table borders
    With oTable.Range.Tables(1)
        With .Borders(Word.WdBorderType.wdBorderLeft)
            .LineStyle = Word.WdLineStyle.wdLineStyleSingle
            .LineWidth = Word.WdLineWidth.wdLineWidth100pt
            .Color = Word.WdColor.wdColorAutomatic
        End With
        With .Borders(Word.WdBorderType.wdBorderRight)
            .LineStyle = Word.WdLineStyle.wdLineStyleSingle
            .LineWidth = Word.WdLineWidth.wdLineWidth100pt
            .Color = Word.WdColor.wdColorAutomatic
        End With
        With .Borders(Word.WdBorderType.wdBorderTop)
            .LineStyle = Word.WdLineStyle.wdLineStyleSingle
            .LineWidth = Word.WdLineWidth.wdLineWidth100pt
            .Color = Word.WdColor.wdColorAutomatic
        End With
        With .Borders(Word.WdBorderType.wdBorderBottom)
            .LineStyle = Word.WdLineStyle.wdLineStyleSingle
            .LineWidth = Word.WdLineWidth.wdLineWidth100pt
            .Color = Word.WdColor.wdColorAutomatic
        End With
        With .Borders(Word.WdBorderType.wdBorderHorizontal)
            .LineStyle = Word.WdLineStyle.wdLineStyleSingle
            .LineWidth = Word.WdLineWidth.wdLineWidth050pt
            .Color = Word.WdColor.wdColorAutomatic
        End With
        With .Borders(Word.WdBorderType.wdBorderVertical)
            .LineStyle = Word.WdLineStyle.wdLineStyleSingle
            .LineWidth = Word.WdLineWidth.wdLineWidth050pt
            .Color = Word.WdColor.wdColorAutomatic
        End With
        .Borders(Word.WdBorderType.wdBorderDiagonalDown).LineStyle = Word.WdLineStyle.wdLineStyleNone
        .Borders(Word.WdBorderType.wdBorderDiagonalUp).LineStyle = Word.WdLineStyle.wdLineStyleNone
        .Borders.Shadow = False
    End With
    oDoc.SaveAs2(pather)
    oDoc.Close()
    oDoc = Nothing
    oWord.Quit()
    oWord = Nothing
    GC.Collect()
    GC.WaitForFullGCComplete()
End Sub

1 Answer 1

2

Your call to exportToWord is apparently running on a thread configured as Threading.ApartmentState.MTA (Backgroundworker threads are Threading.ApartmentState.MTA). Often when you access a control such as this methods does for the datagridview, you will receive a Cross-thread operation not valid error. However this check is run only for such accesses that require the control's Handle property; in this case you are accessing data information from dgv that does not trigger this check.

If you add the following pointless statement to the beginning of exportToWord, an error should be thrown.

Dim handle As IntPtr = dgv.Handle

Access to the Clipboard must be done from a Threading.ApartmentState.STA thread and the UI thread is such a thread. The proper way to do this is to Invoke method on the UI thread where Me is the Form instance:

Me.Invoke(New Action(Of DataGridView, String, ProgressBar)(AddressOf exp.exportToWord), New Object(){dgv, AppDomain.CurrentDomain.BaseDirectory & "Exports\Doublon.docx", prog})

versus the current

exp.exportToWord(dgv, AppDomain.CurrentDomain.BaseDirectory & "Exports\Doublon.docx", prog)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.