OpenFileDialog 类的ShowDialog() 错误的解决
首先,一個(gè)類里,有個(gè)linkLabel1
private OpenFileDialog openFileDialog1;
private DialogResult result;
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
??????? {
??????????? openFileDialog1 = new OpenFileDialog();
??????????? string patch = Application.StartupPath + "\\LOG\\";
??????????? openFileDialog1.InitialDirectory = patch;
??????????? openFileDialog1.Filter = "xls files (*.xls)|*.xls";
????????????result = openFileDialog1.ShowDialog();
??????????? if (result == DialogResult.OK)
??????????? {
??????????????? if (openFileDialog1.FileName != "")
??????????????? {
??????????????????? Process.Start(openFileDialog1.FileName);
??????????????? }
???????????????
??????????? }
???????????
??????? }
就會(huì)報(bào)?
在可以調(diào)用 OLE 之前,必須將當(dāng)前線程設(shè)置為單線程單元(STA)模式。請(qǐng)確保您的 Main 函數(shù)帶有 STAThreadAttribute 標(biāo)記。 只有將調(diào)試器附加到該進(jìn)程才會(huì)引發(fā)此異常。
在測(cè)試小程序里沒有問題,當(dāng)移到大程序里就這樣的問題了。可能是線程多的原因。解決辦法就是添加線程,代碼如下
private Thread invokeThread;
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
??????? {
??????????? openFileDialog1 = new OpenFileDialog();
??????????? openFileDialog1.InitialDirectory = patch;
??????????? openFileDialog1.Filter = "xls files (*.xls)|*.xls";
??????????? invokeThread = new Thread(new ThreadStart(InvokeMethod));
??????????? invokeThread.SetApartmentState(ApartmentState.STA);
??????????? invokeThread.Start();
??????????? invokeThread.Join();
??????????? if (result == DialogResult.OK)
??????????? {
??????????????? if (openFileDialog1.FileName != "")
??????????????? {
??????????????????? Process.Start(openFileDialog1.FileName);
??????????????? }
??????????? }
??????? }
private void InvokeMethod()
??????? {
??????????? result = openFileDialog1.ShowDialog();
??????? }
問題得到解決
轉(zhuǎn)載于:https://www.cnblogs.com/verna/archive/2011/02/15/1955276.html
總結(jié)
以上是生活随笔為你收集整理的OpenFileDialog 类的ShowDialog() 错误的解决的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeapFTP 注册码
- 下一篇: 无废话WPF系列5:控件派生图