首页 > 解决方案 > System.Threading.ThreadStateException: how to solve it?

问题描述

I have a Windows forms Application to open the file dialog, and then view xml files and xlsx files in a datagridview. I wrote the following code, Is my code OK or I need to do something more?

namespace MyFirstWindos
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            openFD.InitialDirectory = "C:";
            openFD.Title = "Insert an File";
            openFD.FileName = "";
            openFD.Filter = "XML Files |*.xml| XLSX Files |*.xlsx ";
            if (openFD.ShowDialog() == DialogResult.OK)
            {
                DataSet ds = new DataSet();
                ds.ReadXml(openFD.FileName);
                dataGridView1.DataSource = ds.Tables[0];
            }
            else
            {
                MessageBox.Show("Operation Cancelled");
            }
        }
    }
}


namespace MyFirstWindos
{
    public static class Program
    {
        public static void Main()
        {
            Compare_D_A d_A = new Compare_D_A();
            d_A.CompareD_A();
            // Compare_D_R d_R = new Compare_D_R();
            //  d_R.compareD_R();   
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

I have this exception

"System.Threading.ThreadStateException: 'The current thread must be set to single thread containment (STA) mode before OLE calls can be made. Make sure that the Main function is marked with STAThreadAttribute.

This exception is only activated if a troubleshooting program is linked to the process, at this row in my code if (openFD.ShowDialog() == DialogResult.OK).

How I can correct it and what it means?

标签: c#.netwinformsexception

解决方案


推荐阅读