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.
Related
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
When I run this I made a dummy "Button1" to test populate the fields they will successfully fill out the texts boxes. How ever I will have it parse that file every minute, and when I do it again I get the error shown below. By adding the routine "DisplayForm_Load" to the button1_click even it would work fine.
My question is I'm pretty sure I shouldn't have to redefine this every time? I think I'm not setting the index back to 0 or something along those lines. From what I've been able to understand from MS website is its like its indexing things in the array that don't exist.
Error received:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication4.exe
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private Directory As String ' Used to hold the folder directory to push/pull data from.
Private FileParser As Microsoft.VisualBasic.FileIO.TextFieldParser
Private Sub PushButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles PushButton.Click
' Sends information to txt file.
' This bit works fine, just writes code to txt file that can be parsed below.
End Sub
Sub DefineTextFieldParse_Load() Handles MyBase.Load
' Instantiate teh TextFieldParser and the set the delimiter
Dim FileName As String = "C:\Users\Caleb\Documents\TestDoc.txt"
Try
FileParser = New FileIO.TextFieldParser(FileName) '' Selects File to Parse
FileParser.TextFieldType = FieldType.Delimited
FileParser.SetDelimiters(",")
Catch ex As Exception
' Errors
MessageBox.Show("Unable to read the file" & "," & FileName)
End Try
End Sub
Sub UpdateCheck()
' Checks share txt file for update.
Dim FileName As String = "C:\Users\<Me>\Documents\TestDoc.txt"
Dim FieldString() As String
'Read the file
If Not FileParser.EndOfData Then
FieldString = FileParser.ReadFields()
' 1st Field
NIS1TextBox.Text = FieldString(0)
' 2nd Field
NIS2TextBox.Text = FieldString(1)
' You get the idea...All Testboxes identified above in the write section
' Repeats 12 more times...
EODTextBox.Text = FieldString(14)
InfoRichTextBox.Text = FieldString.LastOrDefault()
End If
End Sub
Sub PushUpdate()
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
'DefineTextFieldParse_Load()_Load() ' When Enabled code works fine when commented out generates alert.
UpdateCheck()
End Sub
End Class
mchihinney - I did review https://msdn.microsoft.com/en-us/library/hks5e2k6.aspx
However what I found was the issue was with the formatting of the text file. The problem I found was with the text file there was a second line which was blank, so when it tried to parse nothing it through the error. Deleting the second line from the .txt file and worked as expected.
Hi i have a textbox which displays a bunch of names on it. The names are within a string called "strNames". I'm trying to have a save button which saves the names as a txt file in a predetermined location. Here is the code for the save button. It creates the file but without the list of names. please help!
Given the fact that your strNames is an array of strings then you could use File.WriteAllLines, no need to use a StreamWriter here
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
File.WriteAllLines("C:\Test.txt", strNames)
End Sub
This has an advantage against the StreamWriter approach if you don't need particular processing to your input array before writing it to file, no foreach around the array strings and also you don't need to encapsulate the StreamWriter in a Using statement to ensure a proper release of the system resources
You need to write to the file and then call Close() on the StreamWriter
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim w As IO.StreamWriter
w = New IO.StreamWriter("C:\Test.txt")
' strNames is an array so you have to iterate through the array and write each element
For Each item As String In strNames
w.WriteLine(item)
Next
w.Close()
End Sub
Make sure to use Try/Catch blocks in case any exception occurs during accessing and writing to the file.
Also, when you use resources such as Files, make sure to properly dispose of the object that's connected to the resource. Using the 'Using' statement is a great and safe way to do that. Here's an example of both in action.
Sub WriteToFile()
Dim strNames As String() = {"John", "Jimmy", "Joe"}
Try
Using oWriter As New IO.StreamWriter("C:\testFile.txt")
For Each strName As String In strNames
oWriter.WriteLine(strName)
Next
End Using
Catch ex As Exception
HandleException(ex)
End Try
End Sub
I am trying to create text file with the code below; but there is always an extra line at the end that I cannot get rid of. Is there any way to modify this code to write the text file without the last line?? Help appreciated:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MekdamFile As String
MekdamFile = "C:\TEMP\MEKDAM.txt"
Dim dones As New List(Of String)
For i = 1 To 10
dones.Add("test test " & i)
Next
Using sw As New StreamWriter(MekdamFile)
For Each i As String In dones
sw.WriteLine(i)
Next
End Using
End Sub
End Class
Thanks for help in advance...
StreamWriter.WriteLine always writes a line terminator.
On the last iteration of the loop you could use sw.Write instead.
Your code can be simplified a bit:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
File.WriteAllText("C:\TEMP\MEKDAM.txt", [String].Join( _
Environment.NewLine, _
Enumerable.Range(1, 10).[Select](Function(i) "Test test" + Cstr(i))))
End Sub
You are calling WriteLINE, so whatever you pass into it will be appended with a newline character sequence.
If you don't want to write the newline, use Write instead of WriteLine. Of course, you should then append the newline yourself for all lines except the last.
Alternatively, for a small text, just build the whole text, then trim the end of it and write it at once:
Dim sb As new StringBuilder();
For i = 1 To 10
sb.AppendLine("line " + i);
Next
File.WriteAllText(path, sb.ToString().TrimEnd());
I implemented this event of the FileSystemWatcher:
Private Shared Sub OnCreated(source As Object, e As FileSystemEventArgs)
If e.Name.ToUpper() == "MYTEXTFILE.TXT" then
' code '
End If
End Sub
Is there a way to monitor if created files are in a textbox similar to this?
Private Shared Sub OnCreated(source As Object, e As FileSystemEventArgs)
If e.Name.ToUpper.contains(textbox1.text) then
' code '
End Sub
Having more than one file in a multiline textbox and every filename is in a separate line requires that you should split the filenames individually and then check each one with the file just created.
Private Shared Sub OnCreated(source As Object, e As FileSystemEventArgs)
' Get an array of the files at each line and remove eventually spurious empty lines
Dim files() = textbox1.Text.Split(New String() {Environment.NewLine}, _
StringSplitOptions.RemoveEmptyEntries)
Dim newFile = e.Name.ToUpper()
for each file in files
if file.ToUpper() = newFile Then
' code '
Exit For
End If
Next
End Sub
I'm not 100% clear I understand your question, but I'm assuming that you want to compare the name of the file that was just created with the name of a file in a textbox.
1) Is the text in the textbox also uppercase? I see you uppercase the name of the file before comparing.
2) Is the text in the textbox "containable" in the name of the file, maybe the other way around?
3) Should the condition be .Equal instead of .Contains?