2013-03-08 50 views
0

我想实现一个OpenFileDialog框,它的工作正常,除非我选择单击取消然后程序抛出一个错误,说该文件无法找到,这使我困惑,因为我没有选择一个文件。在OpenFileDialog框中取消抛出错误

以下是代码。我如何实现取消按钮?

OpenFileDialog1.InitialDirectory = "C:\" 
OpenFileDialog1.FileName = "Select a Batch file..." 
OpenFileDialog1.Filter = "Batch files (*.bat) | *.bat" 
OpenFileDialog1.ShowDialog() 

If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.Cancel Then 
    OpenFileDialog1.Dispose() 
End If 

Dim R As New IO.StreamReader(OpenFileDialog1.FileName) 
TextBox4.Text = R.ReadToEnd 
R.Close() 

Button4.Enabled = True 
Button6.Enabled = True 
+0

嗯。我不明白为什么这让你感到意外:你不处理用户取消对话的情况。 – 2013-03-08 14:25:37

+0

我该怎么做? – 2013-03-08 14:27:15

回答

0
 Dim result = OpenFileDialog1.ShowDialog() 

    If result = True Then 
     Dim R As New IO.StreamReader(OpenFileDialog1.FileName) 
     TextBox4.Text = R.ReadToEnd 
     R.Close() 

    Button4.Enabled = True 
    Button6.Enabled = True 
    else 
     ' handle the error, e.g. msgbox (no vaild file chosen" 
    End If 
+4

“ShowDialog”的返回类型不是布尔值。 – 2013-03-08 14:57:31

2

您注释掉撤销对话框的处理(不足)。将它放回:

Dim openFileDialog1 As New OpenFileDialog() 
openFileDialog1.Filter = "Batch files (*.bat)|*.bat|All files|*.*" 
Dim result = openFileDialog1.ShowDialog() 

If result = DialogResult.Cancel Then 
    Return ' Just leave the method 
End If 

' … rest of method 

你也应该考虑合理的变量名。 OpenFileDialog1TextBox3Button2都是从来没有适当的名称。好的标识符会极大地提高代码的可读性。

+1

轻微校正Dim result As DialogResult = openFileDialog1.ShowDialog() – dbasnett 2013-03-08 15:20:50

+0

@dbasnett不必要的,不推荐使用'Option Infer On'。 – 2013-03-08 15:46:55

+0

专门定义类型,恕我直言,总是更好。 – dbasnett 2013-03-08 15:59:56

2

对话框将处置本身在这两种情况下 - 你只是如果用户取消他的意图动作没有做任何事情。这应做到:

OpenFileDialog1.InitialDirectory = "C:\" 
OpenFileDialog1.FileName = "Select a Batch file..." 
OpenFileDialog1.Filter = "Batch files (*.bat) | *.bat" 
OpenFileDialog1.ShowDialog() 

If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then 

    Dim R As New IO.StreamReader(OpenFileDialog1.FileName) 
    TextBox4.Text = R.ReadToEnd 
    R.Close() 

    Button4.Enabled = True 
    Button6.Enabled = True 

End If 

当然,你将不得不添加一些额外的错误处理但那是另一回事。

+1

耶的YouTube总不是那么好笑 – 2013-03-11 12:35:13

+1

感谢这个! – Brady 2015-03-18 16:46:54

0

这是我为我的项目工作。

Dim bResult As DialogResult = sfdReportFile.ShowDialog() 

    If bResult = DialogResult.OK Then 
     tbFilePathName.Text = sfdReportFile.FileName.ToString 
    End If 

您需要将结果定义为DialogResult,以检查它是否正常并将文件路径发送到您需要的任何地方。

0

在我的项目中,我使用了SaveFileDialog。如果用户关闭了对话窗口,则没有文件名称,并且发生错误。用我的下面的代码,我的进程不会运行,除非有一个文件名来使用。

If SaveFileDialog1.FileName = Nothing Then 

Else 
    Code to run here when a file name is selected. 
End If 

可以为OpenFileDialog运行同样的事情。只需添加一个if then来检查文件名是否已保存,如果没有,请不要运行代码。