非常友好,堆栈溢出的智能成员向我展示了如何使用' Do Until'并生成消息框以使用户能够保存文件或重命名文件(如果已存在)。但是,我还在撞墙。我无法在我的for循环中保存ListView数据,我在输入框中选择了文件名(参见下面的代码)。它就像我有两个独立的代码片段,因为rtb将数据保存在名为Test.txt的富文本文件中,而saveFile与此无关!请帮忙
代码
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 NEXT bit of code saves 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\SMITH\Documents\Visual Studio 2013\Projects\Test.txt", _
RichTextBoxStreamType.PlainText)
答案 0 :(得分:2)
当您尝试使用RichTextBox方法SaveFile保存文件时,您需要能够使用接收用户输入的变量filePath
。但是这个变量是在块Do Do ....循环内声明的,并且根据scope rules of variables in VB.NET在该块之外是不可用的。您可以在进入循环之前移动变量的声明
Dim fileSaved As Boolean
Dim filePath As String
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
filePath = 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
' The remainder of your code can be left unchanged until the SaveFile line
现在你可以在通话中使用它
rtb.SaveFile(filePath, RichTextBoxStreamType.PlainText)