index was outside the bounds - vb.net

my code is not working please, help
Private Sub Form3_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
Dim lblControls() As Label = {lblName, lblID, lblGender, lblBirthDate, lblCity, lblContactNumber, lblAddress, lblHistory}
Dim sReader As New System.IO.StreamReader(Form1.pathStorage & "Patients\" & selectedPatient & "\patientInfo.txt")
Dim strValues(11) As String
Dim counter As Integer = 0
While sReader.Peek <> 1
strValues(counter) = sReader.ReadLine
counter += 1
End While
counter = 0
For Each lbl As Label In lblControls
lbl.Text = strValues(counter)
counter += 1
Next
sReader.Close()

I have changed to the File class to accomplish your task. You do not need to declare an instance of File. A StreamReader needs to be not closed but disposed. A Using...End Using block or Try...Finally...End Try to ensure the closing and disposing of a StreamReader so the File class is easier to use.
You do not need to declare a size for the strValues because it is initialize at declaration. I added a check that the two arrays are the same size.
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
Dim lblControls() As Label = {lblName, lblID, lblGender, lblBirthDate, lblCity, lblContactNumber, lblAddress, lblHistory}
Dim path As String = pathStorage & "Patients\" & selectedPatient & "\patientInfo.txt"
Dim strValues = File.ReadAllLines(path) 'Returns a string array
If lblControls.Length <> strValues.Length Then
MessageBox.Show("Labels do not equal data.")
Return
End If
Dim counter As Integer = 0
For Each lbl As Label In lblControls
lbl.Text = strValues(counter)
counter += 1
Next
End Sub

Related

How to browse from bottom to top of a text file in vb.net?

I cannot get my code below to work correctly, in fact I want to press a back button in order to go up the lines one by one of a text file then I cut the chain into 3 parts.
Dim LinesOfText() As String = System.IO.File.ReadAllLines("c:\essai.librairie", Encoding.UTF8)
For line As Integer = LinesOfText.Length - 1 To 0 Step -1
Dim currentLine As String = LinesOfText(line)
Dim value As String = currentLine
Dim startIndex As Integer = 0
Dim length As Integer = 17
Dim substring As String = value.Substring(startIndex, length)
Dim subs As String = value.Substring(17, 90)
Dim subst As String = value.Substring(107, 120)
TextBox1.Text = substring
TextBox2.Text = subs
TextBox3.Text = subst
Next
If you store the lines and a line counter so that they are in scope where needed, you can do it like this:
Imports System.IO
Public Class Form1
Dim lines As String()
Dim currentLine As Integer = -1
Sub LoadData(filename As String)
lines = File.ReadAllLines(filename)
currentLine = lines.Length - 1
End Sub
Sub ShowCurrentLine()
If currentLine >= 0 Then
TextBox1.Text = lines(currentLine).Substring(0, 3)
TextBox2.Text = lines(currentLine).Substring(4, 3)
TextBox3.Text = lines(currentLine).Substring(8, 3)
lblLineNo.Text = (currentLine + 1) & "/" & lines.Length
Else
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
lblLineNo.Text = "-"
End If
End Sub
Private Sub bnNext_Click(sender As Object, e As EventArgs) Handles bnNext.Click
If currentLine < lines.Length - 1 Then
currentLine += 1
ShowCurrentLine()
End If
End Sub
Private Sub bnPrev_Click(sender As Object, e As EventArgs) Handles bnPrev.Click
If currentLine > 0 Then
currentLine -= 1
ShowCurrentLine()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadData("C:\temp\SO67209265.txt")
ShowCurrentLine()
End Sub
End Class
You will need to set the substring parameters for your data—I just used a small text file—and the filename to be loaded.
The label lblLineNo is used to show the current line number, starting at 1.

need histogram from these results VB.net

I need some help with the histogram. My program counted the words with three, four, five and six letters. Now I need to make simple histogram from the received answers. This is my code:
Public Class Form1
Dim tekst As String
Dim rijec() As String
Dim trazena As String
Dim brojac1 As Integer = 1
Dim brojac2 As Integer = 0
Dim brojac3 As Integer = 0
Private Sub btnUcitaj_Click(sender As Object, e As EventArgs) Handles btnUcitaj.Click
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
RichTextBox1.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
End If
End Sub
Private Sub btnPrebroj1_Click(sender As Object, e As EventArgs) Handles btnPrebroj1.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 3
txtTri.Text = ("Number of words: " & count.Count.ToString())
End Sub
Private Sub btnPrebroj2_Click(sender As Object, e As EventArgs) Handles btnPrebroj2.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 4
txtCetiri.Text = ("Number of words: " & count.Count.ToString())
End Sub
Private Sub btnPrebroj3_Click(sender As Object, e As EventArgs) Handles btnPrebroj3.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 5
txtPet.Text = ("Number of words: " & count.Count.ToString())
End Sub
Private Sub btnPrebroj4_Click(sender As Object, e As EventArgs) Handles btnPrebroj4.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 6
txtSest.Text = ("Number of words: " & count.Count.ToString())
End Sub
i need histogram from these results from picture.
Visual Basic actually has a control called a chart which is nice for this kind of situation. I found a tutorial here if you would like to check it out.
I wrote up this function that should work with your code, all you need to do is add a data chart and call it Chart1 and call this function.
Private Sub ShowData()
Chart1.Series.Clear() ' Delete the default data series.
Dim tekst = RichTextBox1.Text
Dim rijec = tekst.Split(CChar(" "))
With Chart1.Series.Add("Word Lengths") ' Add a new series called Word Lengths
For wordLength As Integer = 3 To 6 ' Check every word length from 3 to 6
Dim count = From x In rijec Where x.Length = wordLength ' Count how many words there are
.Points.AddXY(wordLength, count.Count) ' Add a new data point
Next
End With
End Sub
Good luck, I hope this helped!
~Nic

Save clicks to file

I got asked a couple of days ago how to save number of clicks you have done to each button in a program to a small file, to keep track of what is most used. Since it was ages ago i dabbled with visual basic i said i would raise the question here, so here goes.
There are 5 buttons labels Button1-Button5. When a button is clicked it should look for the correct value in a file.txt and add +1 to the value. The file is structured like this.
Button1 = 0
Button2 = 0
Button3 = 0
Button4 = 0
Button5 = 0
So when button1 is clicked it should open file.txt, look for the line containing Button1 and add +1 to the value and close the file.
I have tried looking for some kind of tutorial on this but have not found it so i'm asking the collective of brains here on Stackoverflow for some guidance.
Thanks in advance.
delete file first
new ver ..
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
'line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
Dim f As Integer = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
Dim lineSplited = lineToedit.Split
Dim cnt As Integer = lineSplited.Count
Dim newVal = addCount(CInt(lineSplited.Last()))
lineSplited(cnt - 1) = newVal
lineToedit = String.Join(" ", lineSplited)
line(f) = lineToedit
End If
f = f + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
Me.Refresh()
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Output in myfile.txt
Button1 = 9
Button2 = 2
Button3 = 4
Button4 = 0
Button5 = 20
Create a vb winform Application
Drag on your form 5 buttons (Button1, Button2, ... etc)
copy that :
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If lineToedit.Contains(tmpButton) Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
'lineToedit.Replace(lineSplited.Last, newVal)
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Have fun ! :)CristiC777
try this on vs2013
change If confition
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
'If lineToedit.Contains(tmpButton) = True Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next

How to make a program that would detect the same characters within two strings

so i made this but when i enter a string it would only detect one character
and it wont convert the entered string to lower case too
Dim readme, readme2 As String
Dim j, i As Integer
Dim Compare As Integer
readme = TextBox1.Text
readme2 = TextBox2.Text
readme.ToLower.Substring(i, readme.Length)
readme2.ToLower.Substring(j, readme2.Length)
For i = 0 To readme.Length
For j = 0 To readme2.Length
If readme = readme2 Then
Compare = +1
End If
Next
Next
Label4.Text = Compare`enter code here`
Strings are immutable. You cannot apply a method to a string and expects that string to change in response to the inner operations of that method.
You need to reassign the result of the operation to the same string that you have used to call the method
readme = readme.ToLower()
readme2 = readme2.ToLower()
The second part of your question is more confused, are you trying to count the number of equal chars in the same position?
In that case your loop should be
Dim maxLenToCheck = Math.Min(readme.Length, readme2.Length)
For i = 0 To maxLenToCheck - 1
If readme(i) = readme2(i) Then
Compare += 1
End If
Next
In that loop you set always the Compare to 1, the correct syntax to increment the Compare variable is
Compare += 1
Following your comment below, then I presume that your loop should be written as
Dim Compare = 0
For i = 0 To readme.Length - 1
for j = 0 to readme2.Length -1
If readme(i) = readme2(j) AndAlso _
Not Char.IsWhiteSpace(readme(i)) Then
Compare += 1
End If
Next
Next
Based on the comments in the solution by Steve, the author wants to know the count of letters occurring in both strings, ignoring case and white spaces.
By my count, however, the solution should be 21, not 20. Here is a solution using LINQ that also gives visual feedback on where those letters are located:
Public Class Form1
Private Class LetterCount
Public Letter As Char
Public Count As Integer
Public Overrides Function ToString() As String
Return Letter & " : " & Count
End Function
End Class
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "This is a Test"
TextBox2.Text = "This should be tryed before"
RichTextBox1.ReadOnly = True
RichTextBox1.Font = New Font("MS Courier", 14) ' monospaced font
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = TextBox1.Text & vbCrLf & TextBox2.Text & vbCrLf
Dim charsA As New List(Of Char)(TextBox1.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim charsB As New List(Of Char)(TextBox2.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim DistinctCommonLetters = (From A In charsA, B In charsB Where A = B Select A).Distinct
Dim DistinctCounts =
From Letter In DistinctCommonLetters, C In charsA.Concat(charsB)
Where C = Letter
Group By Letter Into Group
Select New LetterCount With {.Letter = Letter, .Count = Group.Count}
Dim TotalMatches = DistinctCounts.Sum(Function(x) x.Count)
ListBox1.DataSource = DistinctCounts.ToList
Label1.Text = "TotalMatches: " & TotalMatches
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim LC As LetterCount = ListBox1.SelectedItem
RichTextBox1.SelectAll()
RichTextBox1.SelectionColor = Color.Black
Dim index As Integer = RichTextBox1.Find(LC.Letter, 0, RichTextBoxFinds.None)
While index <> -1
RichTextBox1.Select(index, 1)
RichTextBox1.SelectionColor = Color.Red
index = RichTextBox1.Find(LC.Letter, index + 1, RichTextBoxFinds.None)
End While
End Sub
End Class

Making a string from a listbox

I have 2 projects, one which has a highscorelist stored on it, and one which tries to add highscores to that list and retrieve all items on the list. Trying to put items on the list works good, but retrieving the list doesn't work well. Here's the code:
Option Strict On
Option Explicit On
Imports System.Net.Sockets
Imports System.Threading
Public Class Main
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Dim connected As Boolean
Private Sub cmd_start_Click(sender As Object, e As EventArgs) Handles cmd_start.Click
server.Start()
cmd_start.Enabled = False
cmd_stop.Enabled = True
lbl_status.Text = "Running"
lbl_status.ForeColor = Color.Green
tmr.Start()
End Sub
Private Sub cmd_stop_Click(sender As Object, e As EventArgs) Handles cmd_stop.Click
server.Stop()
cmd_start.Enabled = True
cmd_stop.Enabled = False
lbl_status.Text = "Not running"
lbl_status.ForeColor = Color.Red
tmr.Stop()
End Sub
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connected = False
CheckForIllegalCrossThreadCalls = False
End Sub
Dim x As Integer = 0
Private Sub tmr_Tick(sender As Object, e As EventArgs) Handles tmr.Tick
If server.Pending Then
client = server.AcceptTcpClient()
stream = client.GetStream()
tmr.Stop()
read()
Else
tmr.Start()
End If
lbl_mseconds.Text = "Relative time: " & x
x += 1
End Sub
Private Sub SendMessage(message As String)
Dim sendtext() As Byte = System.Text.Encoding.ASCII.GetBytes(message)
stream.Write(sendtext, 0, sendtext.Length)
stream.Flush()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i = 1 To listbox_highscores.Items.Count - 1
tosend &= "," & listbox_highscores.Items(i).ToString
Next
MsgBox(tosend)
SendMessage(tosend)
End If
tmr.Start()
End Sub
End Class
On the other project I have this:
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Friend Sub sendHighscore(name As String, score As Integer)
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#1#" & score & "-" & name)
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
End Sub
Friend Sub getHighscoreList()
ListBox_highscores.Items.Clear()
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
ListBox_highscores.Items.Add("Couldn't connect")
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#2#")
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
read()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = Encoding.ASCII.GetString(rec)
Label2.Text = rectext
For Each item In rectext.Split(",")
ListBox_highscores.Items.Add(item)
Next
End Sub
Then when I use the sub sendHighscore() with a name and score, everything perfectly works and it shows in the other project on the list, but when I use the sub getHighscoreList() the list on the second project only contains the first item from the first list. Does someone has ideas?
Edit: Original answer removed entirely because it wasn't actually the problem (although it did offer improvements). My answer was nearly identical to this one anyway.
After analyzing this project much more closely, the problem with the For..Next loop not returning the expected results is because the strings are being sent back and forth as byte arrays in buffers much larger than necessary (client.ReceiveBufferSize). The actual "strings" received contain large amounts of non-printable characters (garbage) added to the end to fill the buffer. The quick and dirty solution is to remove all non-printable characters:
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, _
"[^\u0020-\u007F]", String.Empty)
The whole Sub would read like this:
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, "[^\u0020-\u007F]", String.Empty)
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i As Integer = 1 To (listbox_highscores.Items.Count - 1)
tosend &= "," & listbox_highscores.Items(i).ToString
Next
SendMessage(tosend)
End If
tmr.Start()
End Sub
Try this, your comma's are off as well...
Dim tosend As String = String.Empty
Dim intCount As Integer = 0
For i As Integer = 0 To listbox.Items.Count - 1
If intCount >= 1 Then
tosend &= "," & listbox.Items(i).ToString
Else
tosend &= listbox.Items(i).ToString
intCount += 1
End If
Next
MessageBox.Show(tosend)
Screenshot THAT IT WORKS!