【问题标题】:Why does my program crash when the "Save As" dialog box is exited?为什么退出“另存为”对话框时我的程序会崩溃?
【发布时间】:2016-02-07 23:23:16
【问题描述】:

每次我进入“另存为”对话框时,如果文件没有保存,程序就会崩溃,但是在保存文件时它可以正常工作。我明白为什么会这样(因为用户退出对话框时文件名无效),但我不知道如何解决。

具体问题是当用户没有保存文件就退出对话框时程序崩溃。

提前感谢您的帮助:)

This is the text to be saved in a txt. file

This is the error I recieve

Private Sub btnSaveDetails_Click(sender As Object, e As EventArgs) Handles btnSaveDetails.Click
    Dim ni As IO.StreamWriter
    Dim itms() As String = {ListBox.Items.ToString}
    Dim save As New SaveFileDialog
    Dim it As Integer
    save.Filter = "*.txt|*.txt|All Files (*.*)|*.*" 
    save.CheckPathExists = True 
    save.ShowDialog(Me)
    ni = New IO.StreamWriter(save.FileName)
    For it = 0 To ListBox.Items.Count - 1
        ni.WriteLine(ListBox.Items.Item(it))
    Next
    MessageBox.Show("File Saved!")
    ni.Close()
End Sub

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及重现所需的最短代码 b>问题本身
  • @Plutonix 期望的行为是程序不会崩溃。具体问题是退出对话框时程序崩溃,而且他提供的代码最短,不能缩水,下次记不住了。
  • ...您错过了问题本身中有关特定错误的部分。错误消息图片的链接没有帮助
  • 如果他们取消了对话,你必须取消保存。这里的所有都是它的。显然这就是用户想要的,他们选择 not 来保存!我无法理解这里的问题。

标签: vb.net


【解决方案1】:

对方法ShowDialog 的调用返回一个DialogResult 类型的值。您需要检查此值是否等于DialogResult.OK,如果是,则仅尝试写入您的文件。如果不是,你应该跳过文件 IO。

类似这样的事情(注意使用Using 块来自动处理需要它的对象):

Private Sub btnSaveDetails_Click(sender As Object, e As EventArgs) Handles btnSaveDetails.Click
    Dim itms() As String = {ListBox.Items.ToString}
    Using save As New SaveFileDialog
        save.Filter = "*.txt|*.txt|All Files (*.*)|*.*" 
        save.CheckPathExists = True 
        If save.ShowDialog(Me) == DialogResult.OK Then
            Using ni As New IO.StreamWriter(save.FileName)
                Dim it As Integer
                For it = 0 To ListBox.Items.Count - 1
                    ni.WriteLine(ListBox.Items.Item(it))
                Next
            End Using
            MessageBox.Show("File Saved!")
        Else
            MessageBox.Show("Save Aborted!")
        End If
    End Using
End Sub

【讨论】:

  • 第 6 行的第二个 = 符号仍然使程序崩溃。一旦我删除了那个 = 标志,程序就可以完美运行。谢谢!
猜你喜欢
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多