StephenT
StephenT

Reputation: 495

ThreadStateException Error on openfiledialog

I get the following error when trying to open a file dialog box in .NET:

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. This exception is only raised if a debugger is attached to the process.

I tried adding STAThread() _ to the beginning of the module but that had no effect. Most of the solutions on this error call for adding STAThread() _ to the main method but I'm not sure what the main method is in a vb.NET application. Can anyone help me out here?

The code for the function that throws the error is below. Thanks.

Protected Sub cmdUploadNew_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdUploadNew.Click

    Dim FileName As String
    Dim FileDialog As New OpenFileDialog

    FileDialog.InitialDirectory = "C:\"
    FileDialog.Filter = "Excel files (*.xlsx)|*.xlsx"
    FileDialog.RestoreDirectory = True

    If FileDialog.ShowDialog() = DialogResult.OK Then

        FileName = FileDialog.FileName

    End If

End Sub

Upvotes: 0

Views: 1678

Answers (1)

T.S.
T.S.

Reputation: 19330

You may not have Sub Main if your application is set to "Enable Application Framework". http://visualstudiomagazine.com/articles/2007/10/01/enable-the-application-framework-in-vb.aspx

1 - Go to project Properties-->Application, and uncheck "Enable Application Framework".

2 - Add a Module to your application and inside that module add

<STAThread()> _
Sub Main()
    Application.Run(New MyFirstForm())
End Sub

3 - Go back to project Properties-->Application, and in "Startup Object" select Sub Main

4 - why sub main:

"Every Visual Basic application must contain a procedure called Main. " ..................................................................Microsoft

http://msdn.microsoft.com/en-us/library/ms235406.aspx

Upvotes: 1

Related Questions