VB.NET how to save listview with savefiledialog - vb.net

Something's wrong in my code, i want to save listview item into text file using savefiledialog.
I'm getting error "Overload resolution failed because no accessible 'WriteAllLines' accepts this number of arguments."
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles ChromeButton3.Click
Dim s As New SaveFileDialog
s.Filter = "text|*.txt"
s.Title = "Save Your Hits"
If s.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each myItem As ListViewItem In ListView1.Items
File.WriteAllLines(myItem.Text & vbNewLine & myItem.SubItems(1).Text & vbNewLine & myItem.SubItems(2).Text & vbNewLine & myItem.SubItems(3).Text & vbNewLine & vbNewLine)
Next
End If
End Sub

Your error
Overload resolution failed
can be corrected by looking at the documentation. It is a good idea to do this with any unfamiliar method. Just google the method followed by "in .net" The first link that came up is https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllines?view=netframework-4.8
And the first topic in the documentation is overloads. I think you can see that none of the overloads match what you tried to pass.
As was mentioned in comments File.Write All lines isn't really appropriate for your purposes. Instead of making all those lines and a double line between records, Make each row a single line separating each field by a comma. I used a StringBuilder which provides a mutable (changeable) datatype (unlike a String which is immutable). Saves the compiler from throwing away and creating new strings on every iteration.
I appended a new line on each iteration containing an interpolated string. An interpolated string starts with the $. This allows you to directly mix in variables enclosed in { } with the literal characters.
After the loop, you convert the StringBuilder to a String and write to the file with the file name provided by the dialog box.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim s As New SaveFileDialog
s.Filter = "text|*.txt"
s.Title = "Save Your Hits"
If s.ShowDialog = DialogResult.OK Then
Dim fileName = s.FileName
Dim sb As New StringBuilder
For Each myItem As ListViewItem In ListView1.Items
sb.AppendLine($"{myItem.Text},{myItem.SubItems(1).Text},{myItem.SubItems(2).Text},{myItem.SubItems(3).Text}")
Next
File.WriteAllText(fileName, sb.ToString)
End If
End Sub

Related

How to get ListView.SubItems

I'm trying to make a program that inputs text into a document depending on the user input, and I am currently displaying it as a ListView.
I can't figure out how to get the SubItem from the item, as this is my current code.
For Each item In ListView1.Items
Dim inputString72 As String = "#bot.command()" + vbNewLine
My.Computer.FileSystem.WriteAllText(
SaveFileDialog1.FileName, inputString72, True)
Dim inputString73 As String = "async def " + item.Text + "(ctx):" + vbNewLine
My.Computer.FileSystem.WriteAllText(
SaveFileDialog1.FileName, inputString73, True)
Dim inputString74 As String = " await ctx.send('" + THE SUBITEM OF THE ITEM GOES HERE + "')" + vbNewLine
My.Computer.FileSystem.WriteAllText(
SaveFileDialog1.FileName, inputString74, True)
Next
I think it would be more efficient to use the .net File class. No need to call the method several times in each iteration. From the docs. "The WriteAllText method opens a file, writes to it, and then closes it. " That is a lot of openning and closing. Build a string with a StringBuilder (which is mutable) and then write once to the file.
I used interpolated strings (it is preceded by a $) which allows you to put a variable directly in a string surrounded by braces.
SubItem indexes start at 0 with the first column. The .Text property of the SubItem will return its contents.
Private Sub WriteListViewToFile(FilePath As String)
Dim sb As New StringBuilder
For Each item As ListViewItem In ListView1.Items
sb.AppendLine("#bot.command()")
sb.AppendLine($"async def {item.Text}(ctx):")
sb.AppendLine($" await ctx.send('{item.SubItems(1).Text}')")
Next
File.WriteAllText(FilePath, sb.ToString)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
WriteListViewToFile(SaveFileDialog1.FileName)
End If
End Sub

Not read text file correct

I want when I read txt file and add in ListBox1.items, add this text http://prntscr.com/on12e0 correct text §eUltra §8[§716x§8].zip not like this http://prntscr.com/on11kv
My code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
My.Computer.FileSystem.CopyFile(
appDataFolder & "\.minecraft\logs\latest.log",
appDataFolder & "\.minecraft\logs\latestc.log")
Using reader As New StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.minecraft\logs\latestc.log")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(" Reloading ResourceManager: Default,") Then
Dim lastpart As String = line.Substring(line.LastIndexOf(", ") + 1)
ListBox1.Items.Add(lastpart)
End If
End While
End Using
My.Computer.FileSystem.DeleteFile(appDataFolder & "\.minecraft\logs\latestc.log")
End Sub
This question is only different from your first question in that your have substituted a ListBox for a RichTextBox. It seems you got perfectly acceptable answers to your first question. But I will try again.
First get the path to the file. I don't know why you are copying the file so I didn't.
Add Imports System.IO to the top of your file. The you can use the File class methods. File.ReadAllLines returns an array of strings.
Next use Linq to get the items you want. Don't update the user interface on each iteration of a loop. The invisible Linq loop just adds the items to an array. Then you can update the UI once with .AddRange.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim appDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\.minecraft\logs\latest.log")
Dim lines = File.ReadAllLines(appDataFolder)
Dim lstItems = (From l In lines
Where l.Contains(" Reloading ResourceManager: Default,")
Select l.Substring(l.LastIndexOf(", ") + 1)).ToArray
ListBox1.Items.AddRange(lstItems)
End Sub
If this answer and the previous 2 answer you got don't work, please lets us know why.

Autocomplete dictionary from a RichTextBox

While this code works fine in my RichTextBox, how do you do it from a dictionary in VB?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'AutoComplete.Add("do")
AutoComplete.Add("double")
AutoComplete.Add("Apple")
AutoComplete.Add("Car")
AutoComplete.Add("Table")
AutoComplete.Add("Plate")
How do you do this from a dictionary in VB?
So this isn't an actual .NET dictionary? Ambiguous title!
Assuming each line is a separate word to populate your 'dictionary':
Public Sub PopulateDict()
For Each word As String In File.ReadAllLines("path")
AutoComplete.Add(word)
Next
End Sub
Something like this, yes?
Simple, you just need to read in the dictionary text file, parse the words from it, and then add them to your ArrayList.
Here's an example:
Private AutoComplete As New ArrayList
Private Sub AddDictionary()
Try
' Create an instance of StreamReader to read from a file.
Using sr As StreamReader = New StreamReader("dictionary.txt")
Dim line As String
Dim pieces As String()
' Read every line in the file
' Split the line by the delimiter
' Add the individual pieces to the AutoComplete ArrayList
Do
line = sr.ReadLine()
pieces = line.Split(" ")
For Each piece In pieces
AutoComplete.Add(piece)
Next
Loop Until line Is Nothing
' Close the dictionary file StreamReader
sr.Close()
End Using
Catch E As Exception
' Let the user know what went wrong.
MsgBox("The dictionary file could not be read:\n" & E.message, _
MsgBoxStyle.Critical, _
"Error loading file!")
End Try
End Sub
Note: I don't know how your dictionary file is formatted, so in my example code I'm just splitting the lines into individual words using spaces.
You could call the AddDictionary() sub from your Form1_Load() method to add the words to the AutoComplete dictionary at startup.

Calling a procedure from its non native form

Ok, so
frmResult populates a ListView with various calculations
frmMenu has an export button (see code below). Pressing this is supposed to export the data in the ListView to a txt file. Currently, this button does not work. It says, List View is undeclared - obviously because the code shown below is not 'seeing' data held in frmResult
Question – how do I call the procedures stored in frmResult so that frmMenu can 'see' it.
Public Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
Dim fileSaved As Boolean
Dim filePath As String
Do Until fileSaved
'Request filename from user
Dim saveFile As String = InputBox("Enter a file name to save this message")
'Click Cancel to exit saving the work
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 filePath String contains the path you want to save the file to.
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(filePath, RichTextBoxStreamType.PlainText)
End Sub
Is this what you mean?
Public Sub Init()
'... (all the code)
End Sub
Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Init()
End Sub
You can call Init() from every form load you want. Maybe you want to create a module and store there your methods.
By the way, you only use Function when your methods needs to return a value.
If your code uses elements of the form (or other objects not constant) you need to pass those to the method, like this:
Public Sub Init(myListView As ListView)
myListView.Items.Add("something")
'...
End Sub
Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Init(ListView1)
End Sub
You can add as many parameters as you need. You have to learn the basics before going ant further.
This is a great piece of literature for those struggling with the basics like myself.
You can write code to access objects on a different form. However, you must fully identify the name of the object by preceding it with the object variable name.
Dim resultsForm As New frmResults
resultsForm.lblAverage.Text = sngAverage.ToString()
In these statements, for example, I have declared an object variable called resultsForm that is linked to the form frmResults. The second statement assigns the string value of sngAverage to the lblAverage label box on the frmResults form.
In my code, I needed to change the line that said:
For Each saveitem As ListViewItem In ListView1.Items
To this:
For Each saveitem As ListViewItem In Results.ListView1.Items
I also needed to make sure that the procedure on formResults was made Public not Private

Using a textbox value for a file name

How do you use a textbox value for VB to save some text to? This is what I have so far:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles butUpdate.Click
Dim ECOLID As String
ECOLID = txtID.Text
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("?", True)
file.WriteLine("ECOL Number:")
file.WriteLine(txtID.Text)
file.Close()
End Sub
The txtID text will determine the title however how can I get it to save it as "C:/Order/'txtID'.txt" for example?
A textbox has a property called Name and this is (usually) the same as the variable name that represent the TextBox in your code.
So, if you want to create a file with the same name of your textbox you could write
file = My.Computer.FileSystem.OpenTextFileWriter(txtID.Name & ".txt", True)
However there is a big improvement to make to your code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles butUpdate.Click
Dim ECOLID As String
ECOLID = txtID.Text
Dim fileName = txtID.Name & ".txt"
Using file = My.Computer.FileSystem.OpenTextFileWriter(fileName, True)
file.WriteLine("ECOL Number:")
file.WriteLine(txtID.Text)
End Using
End Sub
In this version the opening of the StreamWriter object is enclosed in a Using Statement. This is fundamental to correctly release the resources to the operating system when you have done to work with your file because the End Using ensures that your file is closed and disposed correctly also in case of exceptions