VB.NET Read text file line by line and set every line in textbox with button clicks - vb.net

hello i want to read text file line by line and set every lien in textbox eash time i click the button
this is my code and working fine. but i looking for easy way to read large text that has more thean 5 lines ?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Static count As Integer
count = count + 1
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
Dim readLines() As String = IO.File.ReadAllLines(myFile)
If count = 1 Then
TextBox1.Text = readLines(0)
End If
If count = 2 Then
TextBox1.Text = readLines(1)
End If
If count = 3 Then
TextBox1.Text = readLines(2)
End If
If count = 4 Then
TextBox1.Text = readLines(3)
End If
If count = 5 Then
TextBox1.Text = readLines(4)
End If
If count = 6 Then
TextBox1.Text = readLines(5)
End If
End If
End Sub

I think you need to read the file just one time when you load your form (assuming a WinForms example here)
' Declare these two globally
Dim readLines() As String
Dim count As Integer = 0
Private void Form_Load(sender As Oject, e As EventArgs) Handles Base.Load
' In form load, read the file, just one time
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
readLines() As String = IO.File.ReadAllLines(myFile)
else
TextBox1.Text "File not found"
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Check if you have a file and if you don't have reached the last line
if readLines IsNot Nothing AndAlso count < readLines.Length Then
TextBox1.Text = readLines(count)
count += 1
else
TextBox1.Text "End of file"
End If
End Sub

This reduces the amount of code you need to write:
TextBox1.Text = readLines(count - 1)

Related

Add a completely different line with every button click

Complete noob to vb.net (and programming in general) here, all I really want is every time I click a button, the number in the textbox is added by 1 but the new number shows up on the next line. Tried to google this a hundred times but nothing really helped.
I don't want to use loops as I don't want all numbers to show up at once, only for the added number to show up after clicking a specific button (on a new line).
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim txtoutput As String = ""
Dim a As Integer = 1
txtoutput &= "the value of a =" & a & Environment.NewLine
a = a + 1
TextBox1.Text = txtoutput
End Sub
You are replacing the Text, you want to append a new line, so you need to do:
Private a As Int32 = 0
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
a += 1
Dim newLine = $"the value of a = {a}"
TextBox1.Text = TextBox1.Text & Environment.NewLine & newLine
End Sub
You also have to use a field and not a local variable if you want to retain the old value and increment it. Otherwise it is reset always to it's inital value.
Please try to change dim a to static a
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim txtoutput As String = ""
Static a As Integer = 1
txtoutput &= "the value of a =" & a & Environment.NewLine
a = a + 1
TextBox1.Text = txtoutput
End Sub

How to find and highlight next instance of word in richtextbox in visual basic?

Here is the visual basic windows application form I am currently working on.
https://i.snag.gy/EzoXr3.jpg
How can I write code for the find next button like in this video.
https://www.dropbox.com/s/u93h9jn605uhwsu/CPT341Project2Walkthrough.avi?dl=0
If I can get a syntax to store a index variable outside the private sub of findnext button, I can solve the problem. Because everytime I click the findnext button, I have to find the respective instance of that word in the filetext. Or I can apply some code to find it in the substring of remaining text after its first occurrence.
Below is my code:
Public Class Form1
'Enter your name
'Date
'Class - CPT 341 VB.NET NJIT
Private Sub openBtn_Click(sender As Object, e As EventArgs) Handles openBtn.Click
If OpenFileDialog.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
fileText.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialog.FileName)
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Bring the form to the inital state for a different search
Dim temp As String = fileText.Text
fileText.Text = temp
outputIndex.ForeColor = Color.Black
'MessageBox to show error for empty search textbox
If inputText.Text = "" Then
MessageBox.Show("Enter Text to Search", "CPT 341 Fall 2018 - Project 2")
Else
'Declare variables
Dim txt As String : Dim x As Integer = 0 : Dim output As String
txt = inputText.Text
If fileText.Text.IndexOf(txt) <> -1 Then
Dim idx As Integer = CStr(fileText.Text.IndexOf(txt))
outputIndex.Text = idx
'Find and highlight the first word searched in the RichTextBox
fileText.Find(txt, x, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
'populate the string with ANSI numbers
output = Asc(txt(0))
For x = 1 To (txt.Length - 1)
output = output & " " & Asc(txt(x))
Next x
outputANSI.Text = output
ElseIf fileText.Text = "" Then
MessageBox.Show("Please open a file to search from", "CPT 341 Fall 2018 - Project 2")
Else
outputIndex.Text = txt & " is not found"
'Bring the form to inital state
fileText.Text = temp
'Change the index textbox text color to red
outputIndex.ForeColor = Color.Red
'Empty the ANSI textbox
outputANSI.Text = ""
End If
End If
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
Dim txt As String = inputText.Text
Dim Index As Integer = fileText.Text.IndexOf(txt) + txt.Length
'Find and highlight the word searched in the RichTextBox other than first occurrence
fileText.Find(txt, Index, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
Index = fileText.Text.IndexOf(txt, Index) + txt.Length + 1
End Sub
Private Sub btnWords_Click(sender As Object, e As EventArgs) Handles btnWords.Click
wordCount.Text = fileText.Text.Split(" ").Length
End Sub
Private Sub btnChars_Click(sender As Object, e As EventArgs) Handles btnChars.Click
charCount.Text = fileText.Text.Length
End Sub
End Class
Or any other suggestion would be helpful.

VB.NET Read .Txt File Into Multiple Text Boxes

I have a program that I can enter in names and integer values in the text boxes and then save those to a file. That works perfectly fine but the part I need help with is the reading of the file.
The data is saved into the file much like a csv file. example:
Test, 5, 5, 5
dadea, 5, 5, 5
das, 5, 5, 5
asd, 5, 5, 5
dsadasd, 5, 5, 5
My problem is, how do I read that into multiple text boxes on my form?
The names (first value of each row) should go into their corresponding Name textbox (i.e. txtName0, txtName1, txtName2, etc.) and the integer values should also go into their corresponding text boxes (txtCut1, txtColour1, etc.).
I have spent the past 2 hours trying to figure this out but I just cant.
The part I need help with is the last method.
Imports System.IO
Public Class Form1
Private aPricesGrid(,) As TextBox
Private aAverages() As TextBox
Private aNames() As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
aPricesGrid = {{txtCut1, txtColour1, txtUpDo1, txtHighlight1, txtExtensions1},
{txtCut2, txtColour2, txtUpDo2, txtHighlight2, txtExtensions2},
{txtCut3, txtColour3, txtUpDo3, txtHighlight3, txtExtensions3},
{txtCut4, txtColour4, txtUpDo4, txtBHighlight4, txtExtensions4},
{txtCut5, txtColour5, txtUpDo5, txtHighlight5, txtExtensions5}}
aAverages = {txtAvg0, txtAvg1, txtAvg2, txtAvg3, txtAvg4}
aNames = {txtName0, txtName1, txtName2, txtName3, txtName4}
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
For nCol As Integer = 0 To 4
Dim nColTotal As Integer = 0
Dim nColItems As Integer = 0
For nRow As Integer = 0 To 2
Try
nColTotal += aPricesGrid(nRow, nCol).Text
nColItems += 1
Catch ex As Exception
End Try
Next
aAverages(nCol).Text = (nColTotal / nColItems).ToString("c")
Next
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
For Each txt As Control In Me.Controls
If TypeOf txt Is TextBox Then
txt.Text = String.Empty
End If
Next
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim oSaveFileDialog As New SaveFileDialog()
'Display the Common file Dialopg to user
oSaveFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oSaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Retrieve Name and open it
Dim fileName As String = oSaveFileDialog.FileName
Dim outputFile As StreamWriter = File.CreateText(fileName)
For nRow As Integer = 0 To 4
outputFile.Write(aNames(nRow).Text)
For nCol As Integer = 0 To 2
outputFile.Write(", " & aPricesGrid(nRow, nCol).Text)
Next
outputFile.WriteLine()
Next
outputFile.Close()
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub ReadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ReadToolStripMenuItem.Click
Dim oOpenFileDialog As New OpenFileDialog()
'Display the Common file Dialopg to user
oOpenFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oOpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fileName As String = oOpenFileDialog.FileName
Dim OpenFile As StreamReader = File.OpenText(fileName)
End If
End Sub
End Class
Try this method.
Dim mindex as integer
Dim string1 as string()
Dim OpenFile As StreamReader = File.OpenText(fileName)
While OpenFile .Peek <> -1
string1= OpenFile .ReadLine.Split(",")
If mindex = 0 Then
txtname1.text=string1(0)
txtcut1.text=string1(1)
txtcolour1.text=string1(2)
'add other textboxes
ElseIf mindex = 1 Then
txtname2.text=string1(0)
txtcut2.text=string1(1)
txtcolour2.text=string1(2)
'add other textboxes
ElseIf mindex = 2 Then
txtname3.text=string1(0)
txtcut3.text=string1(1)
txtcolour3.text=string1(2)
'add other textboxes
ElseIf mindex = 3 Then
'your code
ElseIf mindex = 4 Then
'your code
End If
mindex += 1
End While
OpenFile .Close()
hope this helps.

For Each Item in ListBox1 do something then add item to listbox2 vb

I made an app to convert certain numbers to other format
i.e
1 = A
2 = B
3 = C
4 = D
5 = E
ETC
I have made that function with no problem and I have been using it for quite sometime, but now I would like to do things faster and in a batch.
So it's really difficult for me to copy from a text file to my Textbox1 then press button1 then copy textbox2 to other text file.
So I was thinking in loading the text file into a List Box then do a loop for each item in that list into a second list that I can export to another text file.
The importing and exporting I have it covered but where I'm stuck at is to make the loop.
Here's what I have please if you know a better way to do it let me know or tell me how to fix it this way.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using FD As New OpenFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
ListBox1.Items.Clear()
ListBox1.Items.AddRange(IO.File.ReadAllLines(FD.FileName))
End If
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Do
Dim Item As String = ""
For Each i As String In ListBox1.Items
Item &= i
TextBox1.Text = Item
TextBox2.Text = MYFUNCTION(TextBox1.Text)
ListBox2.Items.Add(TextBox2.Text)
TextBox1.Text = ""
TextBox2.Text = ""
Next
Loop Until TextBox1.Text = "END"
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'TextBox2.Text = MeidHexToDec(TextBox1.Text)
Using FD As New SaveFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim FileContent As String = ""
For Each i As String In ListBox2.Items
FileContent &= i & vbCrLf
Next
IO.File.WriteAllText(FD.FileName, FileContent)
End If
End Using
End Sub
So my final aim is to do something like this:
TextFile1.txt
1
2
5
5
1
3
2
END
then after the conversion output
TextFile2.txt
A
B
E
E
A
C
B
The text file size will vary sometimes it will have only 10 items sometimes will be 50...
Thanks.
You do not need the Do loop at all and you can simplify the rest of your loop logic, like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each i As String In ListBox1.Items
ListBox2.Items.Add(MYFUNCTION(i))
Next
End Sub
You do not need to look out for the END marker, because everything in the file was read into the ListBox1.Items collection, thus once you have looped through all of the string values in ListBox1.Items, then you are at the end of the file.
The MYFUNCTION logic returns the transformation from number to letter, thus just add the result of that function into ListBox2.Items and you are done.
Public Function Letr(N As Int16) As String
Letr = Chr(N + 64)
End Function

sequential access file in vb

I am working on a program in Visual Basic that incorporates using a sequential access file for a ballot type program. Each type the user clicks the save vote button, the amount of votes gets stored. What I am trying to do is in my access file is to display the number of votes as an actual number. The way my program is written right now, the name of the candidate appears as many times as the vote was saved. for example, if perez was voted for 4 times, in the access file perez is displayed on 4 different lines. How do I display the actual number of how many time they were voted for. I'm thinking using a counter variable, but not really sure how to really implement it in. this is what i have so far.
Public Class Voter
Dim file As IO.File
Dim infile As IO.StreamReader
Dim outfile As IO.StreamWriter
Private Sub Voter_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
outfile = IO.File.CreateText("Votes.txt")
End Sub
Private Sub btnVote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVote.Click
lstResult.Items.Clear()
'which buttons is clicked
If radMark.Checked = True Then
outfile.WriteLine(radMark.Text)
radMark.Checked = False
ElseIf radSheima.Checked = True Then
outfile.WriteLine(radSheima.Text)
radSheima.Checked = False
ElseIf radSam.Checked = True Then
outfile.WriteLine(radSam.Text)
radSam.Checked = False
Else
MessageBox.Show("You should select one among them")
End If
End Sub
Private Sub btnResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResult.Click
'Dim Mark, Sheima, Sam As Integer
Dim Mark As Integer = 0
Dim Sheima As Integer = 0
Dim Sam As Integer = 0
Dim name As String
'Mark = Sheima = Sam = 0
outfile.Close()
infile = IO.File.OpenText("Votes.txt")
'keep track of votes
While Not infile.EndOfStream
name = infile.ReadLine()
If name.Equals("Mark Stone") Then
Mark += 1
ElseIf name.Equals("Sheima Patel") Then
Sheima += 1
Else
Sam += 1
End If
End While
'results
lstResult.Items.Clear()
lstResult.Items.Add("Mark Stone " & CStr(Mark))
lstResult.Items.Add("Shemia Patel " & CStr(Sheima))
lstResult.Items.Add("Sam Perez " & CStr(Sam))
infile.Close()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
End Class
In your btnVote_Click function you are writing the radiobutton text into the file everytime you click on it, that's how the issue to be created.
Also you are counting how many times the name appears in the file as the number of vote but not the number.
You should try putting the name and count in your vote file rather than just the name, e.g.
Mark,1
Sheima,2
Same,5
Then when you click Vote button, you should read the number for Mark, increment by 1 and write it back.
Try this,
Private Sub btnVote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVote.Click
lstResult.Items.Clear()
'which buttons is clicked
If radMark.Checked = True Then
AddCount(radMark.Text)
radMark.Checked = False
ElseIf radSheima.Checked = True Then
AddCount(radSheima.Text)
radSheima.Checked = False
ElseIf radSam.Checked = True Then
AddCount(radSam.Text)
radSam.Checked = False
Else
MessageBox.Show("You should select one among them")
End If
End Sub
Private Sub btnResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResult.Click
'results
lstResult.Items.Clear()
lstResult.Items.Add("Mark Stone " & GetCount(radMark.Text))
lstResult.Items.Add("Shemia Patel " & CStr(radSheima.Text))
lstResult.Items.Add("Sam Perez " & CStr(radSam.Text))
End Sub
Private Sub AddCount(Byval VoteName As String)
infile = New IO.File.StreamReader("Votes.txt")
Dim whole_line As String
Dim person As String
Dim vote_count As Integer
Dim found as boolean
'read through the whole file until the end or find the name
Do While infile.Peek() >= 0 And person <> VoteName
'read each line
whole_line = infile.ReadLine
person = Split(whole_line, ",")(0)
If person = VoteName Then
vote_count = Split(whole_line, ",")(1)
found = True
End If
Loop
'Close the file after it is used.
infile.Close()
'Reopen the file with the StreamWriter
outfile = IO.File.OpenText("Votes.txt")
If found = True Then
'the line will only be replace if the person name is found in the line
whole_line = Whole_line.replace(VoteName & "," & vote_count, VoteName & "," & vote_count + 1)
'Write back into the file
outfile.WriteLine(whole_line)
Else
'if the vote name is not found in the file
'Then create a new one
outfile.WriteLine(VoteName & ",1" & VbCrLf)
End If
outfile.Close()
End Sub
Private Function GetCount(Byval VoteName As String)
infile = New IO.File.StreamReader("Votes.txt")
Dim whole_line As String
Dim person As String
Dim vote_count As Integer
'read through the whole file
Do While infile.Peek() >= 0 And person <> VoteName
'read each line
whole_line = infile.ReadLine
person = Split(Whole_line, ",")(0)
If person = VoteName Then
vote_count = Split(whole_line, ",")(1)
End If
Loop
infile.Close()
Return vote_count
End Sub