Search code examples
c#multithreadingexcelexcel-2007sta

Getting STA error when try to open OpenFileDialog box in Excel addin project


I have created Excel addin project using Visual Studio to insert a data into database.

The problem is I'm unable to open a File upload box in this.

I am getting an error.

My code:

 [ObsoleteAttribute()]
        [STAThread]
        private void Save(ProgressBarForm pBar)
        {
  OpenFileDialog openFileDialog1 = new OpenFileDialog();
                        DialogResult result =  openFileDialog1.ShowDialog();
                        if (result == DialogResult.OK)
                        {
//execute code

I tried to give attribute to Save method also then also it is giving me the error below:

enter image description here


Solution

  • You need to put the [STAThread] on your Main method, like so:

    [STAThread]
    static void Main()
    {
    

    Alternatively, start a new thread for saving, along these lines:

    var thread = new Thread(mySaveMethod);
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();