【问题标题】:How to open "openFileDialog" by button click? [duplicate]如何通过单击按钮打开“openFileDialog”? [复制]
【发布时间】:2020-11-26 10:05:23
【问题描述】:

我想通过点击按钮来打开openFileDialog。但我所有的努力都没有成功。

我试过了:

private void button1_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == DialogResult.OK)

            {
                Class1 excel = new Class1(dialog.InitialDirectory, 1);
                string path = dialog.InitialDirectory + ".txt"; //this is to create a text document with the same name
                TextWriter tw = new StreamWriter(path, true);

                tw.Write(excel.ReadCell(0, 0));
                tw.Close();
            }
        }

似乎总是有什么事情发生,但窗口马上消失了。

有人知道你的建议吗?

谢谢

【问题讨论】:

  • 可能该按钮的 DialogResult 属性未设置为 None。
  • @TaW 好点了吗?
  • 那么现在是学习的时候了!真的 !!只需在带有 showdialog 的行添加一个断点并执行一次。要设置断点,请单击行号左侧的灰色部分。它将创建一个深红色的圆圈.. - 按 F11 步进!
  • 您确实设置了断点?然后启动程序?如果没有按 F5 !现在您的按钮应该会出现,当您单击它时,调试器应该会在断点处停止..

标签: c# winforms button openfiledialog


【解决方案1】:

你能试试这个吗?

            using (OpenFileDialog upload = new OpenFileDialog())
                {
                    upload.Filter = "Txt Files|*.txt";
                    upload.Title = "Select File";
                    if (upload.ShowDialog() != DialogResult.OK)
                        return;
                    string filePath= upload.FileName;
                    this.fileName = Path.GetFileName(fileName);
                }

【讨论】:

  • 只为 openfiledialog 设置过滤器
  • 也使用 using 语句。当我需要通过单击按钮打开文件对话框时,此代码对我有用。我觉得问题可能出在使用语句上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 2017-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 2018-10-29
相关资源
最近更新 更多