我有以下代码,在保存文件时效果很好。但是当保存“到”对话框打开时,带有“保存”或“取消”选项.....当我单击取消时,我得到并且异常错误。 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()
答案 0 :(得分: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