2013-03-08 43 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來檢查文件名是否已保存,如果沒有,請不要運行代碼。