使用是/否消息框保存ListView数据

时间:2015-09-01 12:42:19

标签: vb.net listview

我已经使用了100%的代码作为解决方案在这里(我非常感激),但仍然打成了墙。问题是我仍然无法使用我选择的文件名保存文件(请参阅InputBox),这是因为它与代码中的rtb不同。我如何将两者合并?

代码

Dim fileSaved As Boolean

Do Until fileSaved
    Dim saveFile As String = InputBox("Enter a file name to save this message")
    If saveFile = "" Then Exit Sub
    Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
    Dim filePath As String = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")

        fileSaved = True
        If My.Computer.FileSystem.FileExists(filePath) Then
            Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
            Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
            fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
        End If
    Loop

    'THIS CODE save content to Test.txt NOT saveFile as desired
    Dim rtb As New RichTextBox
    rtb.AppendText("Generation, Num Of Juveniles, Num of Adults, Num of Semiles, Total" & vbNewLine)
    For Each saveitem As ListViewItem In ListView1.Items
        rtb.AppendText(
                       saveitem.Text & ", " &
                       saveitem.SubItems(1).Text & ", " &
                       saveitem.SubItems(2).Text & ", " &
                       saveitem.SubItems(3).Text & ", " &
                       saveitem.SubItems(4).Text & vbNewLine)
    Next
    rtb.SaveFile("C:\Users\RICHARD\Documents\Visual Studio 2013\Projects\Test.txt", _
    RichTextBoxStreamType.PlainText)

1 个答案:

答案 0 :(得分:1)

以下代码循环,直到设置布尔变量以指示数据已保存。

Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    Dim fileSaved As Boolean 
    Do Until fileSaved 
        Dim saveFile As String = InputBox("Enter a file name to save this message")
        If saveFile = "" Then Exit Sub
        Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments 
        Dim filePath As String = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")

        fileSaved = True
        If My.Computer.FileSystem.FileExists(filePath) Then
            Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
            Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
            fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes) 
        End If
    Loop

    'your code to save the data goes here
    'the filePath String contains the path you want to save the file to.
End Sub

[编辑]更正逻辑并创建一个filePath变量来存储文件的路径。还添加了代码以允许用户通过输入空字符串退出。