2013-10-30 57 views
0

我有以下代碼在保存文件時運行良好。但是,當「保存」對話框打開「保存」或「取消」選項.....當我點擊取消我得到和異常錯誤在這裏。 W.WriteLine(gradesListBox.Items(1).ToString)如何我會解決這個問題?我還奇怪試過,但沒有與它的任何地方獲得。如何保存文件並且不會拋出異常錯誤

If result <> Windows.Forms.DialogResult.Cancel Then 
     Close() 
    End If 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim result As DialogResult 

    'Writes txt File to C: Drive 
    SaveFileDialog1.InitialDirectory = ("C:\") 
    SaveFileDialog1.FileName = ("Save As...") 
    SaveFileDialog1.Filter = ("Only Text Files (*.txt)|*.txt") 
    SaveFileDialog1.ShowDialog() 

      Dim W As New IO.StreamWriter(SaveFileDialog1.FileName, True) ' writes specified information to save file 
    W.WriteLine(lblTimeDate.Text & "    " & txtJobFileName.Text) 
    W.WriteLine() 'Writes Blank Line 
    W.WriteLine() 

    'Formats Write to save file  
    W.WriteLine(vbTab & gradesListBox.Items(0).ToString) 
    W.WriteLine(gradesListBox.Items(1).ToString) 
    W.WriteLine(gradesListBox.Items(2).ToString) 
    W.WriteLine(gradesListBox.Items(3).ToString) 
    W.WriteLine(gradesListBox.Items(4).ToString) 
    W.WriteLine(gradesListBox.Items(6).ToString) 
    W.WriteLine(gradesListBox.Items(9).ToString) 
    W.WriteLine(gradesListBox.Items(7).ToString) 
    W.WriteLine(gradesListBox.Items(8).ToString) 
    W.WriteLine(gradesListBox.Items(9).ToString) 
    W.WriteLine(gradesListBox.Items(10).ToString) 
    W.WriteLine() 
    W.WriteLine() 

回答

1
If SaveFileDialog1.ShowDialog <> DialogResult.Cancel Then 
    ' do all that stuff 


End If 

,你有對話的結果變量,但沒有用它。你不需要在指定每個項目列表框(當數以百計的項目時它會變得非常單調乏味):

For n as integer=0 to gradesListBox.items.count-1 
    W.WriteLine(gradesListBox.Items(n).ToString) 
next n 
+0

這是一個非常簡單的解決方法,謝謝。離子但將保存另一次 –