单击保存按钮后如何显示消息框错误/成功

时间:2016-02-18 14:49:00

标签: vb.net listbox save messagebox

我一直在网上搜索解决方案,但由于某种原因似乎找不到它。

我想显示一个消息框,或者说" Saved Successfully"或者是一个错误信息,当"保存"单击按钮。

到目前为止,这是按钮的代码:

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveKeywords.Click

    IO.Directory.CreateDirectory("C:\TESTING")
    Dim w As New IO.StreamWriter("C:\TESTING\Keywords.txt")
    Dim i As Integer

    For i = 0 To ListBox1.Items.Count - 1
        w.WriteLine(ListBox1.Items.Item(i))
    Next
    w.Close()


End Sub

非常感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用Try Catch来检测程序中的错误,因此如果错误则会发送错误消息。例如:

manyToOne

即使成功保存或错误,finally也将始终关闭流写器流。

另一方面,我会亲自以这种方式写文件,

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveKeywords.Click

Try 

IO.Directory.CreateDirectory("C:\TESTING")
Dim w As New IO.StreamWriter("C:\TESTING\Keywords.txt")
Dim i As Integer

For i = 0 To ListBox1.Items.Count - 1
    w.WriteLine(ListBox1.Items.Item(i))
Next

MessageBox.Show("Saved Successfully")

Catch ex as exception

Messagebox.show("Error when saving. " & ex.tostring, "Data error ")

Finally
w.Close()

End Try

End Sub

(以上行未经测试,因此ListBox1.ToArray可能无法正常工作,但如果没有,则很容易修复

答案 1 :(得分:0)

理想情况下,按钮点击应包含尽可能少的代码,并调用包含下面代码的大部分代码的子或函数,但这不是问题。

您应尽可能检查代码中的错误 - 在您的情况下检查目录是否已存在。

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveKeywords.Click
    SaveFile("C:\TESTING\Keywords.txt")
End Sub

Private Sub SaveFile(fileName As String)
    If Not Directory.Exists(Path.GetDirectoryName(fileName)) Then
        IO.Directory.CreateDirectory(path.GetDirectoryName(fileName))
    End If
    Dim w As New IO.StreamWriter()
    Dim i As Integer
    Try
        For i = 0 To ListBox1.Items.Count - 1
            w.WriteLine(ListBox1.Items.Item(i))

        Next
    Catch ex As Exception
        MessageBox.Show("Error saving File: " & fileName & vbCrLf & "Exception Details" & vbCrLf & ex)
    Finally
        w.Close()
End Sub