Ordering numbers highest to lowest - vb.net

For a highscore page in my game I am taking the 1st to 5th highest values from a text file and then displaying them in a text box but I am having the issue that my code is seeing each digit as a separate number, an example being that 43 will be read as 4 and 3. This means my highsore page never shows a score above 9. The text file is in the rescources if the program and contain a new number on each line.
How do i fix this?
Code Below.
'Part 1: Determine Resource File Path based on Debugging mode or Published mode
Dim ResourceFilePathPrefix As String
If System.Diagnostics.Debugger.IsAttached() Then
'In Debugging mode
ResourceFilePathPrefix = System.IO.Path.GetFullPath(Application.StartupPath & "\..\..\resources\")
Else
'In Published mode
ResourceFilePathPrefix = Application.StartupPath & "\resources\"
End If
'Part 2: Write the text file
Dim lines() As String = File.ReadAllLines(ResourceFilePathPrefix & "scores.txt")
Array.Sort(lines)
Array.Reverse(lines)
P1Score.Text = lines(0)
P2Score.Text = lines(1)
P3Score.Text = lines(2)
P4Score.Text = lines(3)
P5Score.Text = lines(4)

You need to convert the scores into integers before you can sort them numerically otherwise they will be sorted as text (which is how the scores are stored in the file).
'Part 2: Write the text file
Dim lines() As String = File.ReadAllLines(ResourceFilePathPrefix & "scores.txt")
Dim scores As New System.Collections.Generic.List(Of Integer)
For Each line As String in lines
scores.Add(Convert.ToInt32(line))
Next
scores.Sort()
scores.Reverse()
P1Score.Text = scores(0)
P2Score.Text = scores(1)
P3Score.Text = scores(2)
P4Score.Text = scores(3)
P5Score.Text = scores(4)
Or using Linq:
'Part 2: Write the text file
Dim lines() As String = File.ReadAllLines(ResourceFilePathPrefix & "scores.txt")
Dim scores = lines.Select(Function(x) Convert.ToInt32(x)).OrderByDescending(Function(x) x)
P1Score.Text = scores(0)
P2Score.Text = scores(1)
P3Score.Text = scores(2)
P4Score.Text = scores(3)
P5Score.Text = scores(4)

Related

Alpha-numeric barcodes in datagridview

I have created a barcode label printing app in vb. net using visual studio 2010. I have managed to successfully generate alpha-numeric numbers into the datagridview and the barcodes in the image column but instead of printing from 1A-1D, the barcode only prints the 1A when scanned. Please can someone tell me what I’m doing wrong, I’ve been trying to do this for the past few days, but nothing seems to work. Help much appreciated.
Dim alphaNumeric As String = String.Empty
Dim number As String = txtSubNo.Text
Dim alphabet As String = txtAlpha.Text
Dim loopValue As String = txtNo..Text
For index As Integer = 0 To loopValue - 1
alphaNumeric = number.ToString & alphabet
DataGridView1.DataSource = Nothing
DataGridView1.ColumnCount = 4
DataGridView1.Columns(0).Name = "LAB No"
DataGridView1.Columns(1).Name = "SUBNO"
DataGridView1.Columns(2).Name = "INDICATOR"
DataGridView1.Columns(3).Name = "BARCODE"
DataGridView1.Rows.Add(txtLabNo.Text, "" & alphaNumeric, Indicator.Text, PictureBox1.image)
If Asc(alphabet) + 1 <= 90 Then
alphabet = Chr(Asc(alphabet) + 1)
Else
alphabet = "A"
End If
Next
End If

VB - Sorting Alphabetically From a CSV File

I don't know a lot about the subject of sorting but here goes: I am trying to sort a music library (comma seperated in a csv file. Some examples):
1,Sweet Home Alabame,Lynyrd Skynyrd,4:40,Classic Rock
2,Misirlou,Dick Dale,2:16,Surf Rock
I need to sort them alphabetically (by title of track) but I don't know two things: 1. Why my current technique isn't working:
Dim array() As String = {}
sr = New StreamReader("library.csv")
counter = 1
Do Until sr.EndOfStream
array(counter) = sr.ReadLine()
counter += 1
Loop
System.Array.Sort(Of String)(array)
Dim value As String
For Each value In array
Console.WriteLine(value)
Next
Console.ReadLine()
I don't know if this is the best way of sorting. I then need to display them as well. I can do this without sorting, but can't figure out how to do it with sorting.
Help please (from people who, unlike me, know what they're doing).
Right now you're putting all fields in one long string of text (each row).
In order to sort by a particular field, you'll need to build a matrix of rows and columns. For example, a DataTable.
Here's a class that should do the trick for you:
https://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F
Here's the sample usage code from the article, translated to VB:
Public Class CsvImporter
Public Sub Import()
Dim dsResult As DataSet
' Using an XML Config file.
Using parser As New GenericParserAdapter("MyData.txt")
parser.Load("MyData.xml")
dsResult = parser.GetDataSet()
End Using
' Or... programmatically setting up the parser for TSV.
Dim strID As String, strName As String, strStatus As String
Using parser As New GenericParser()
parser.SetDataSource("MyData.txt")
parser.ColumnDelimiter = vbTab.ToCharArray()
parser.FirstRowHasHeader = True
parser.SkipStartingDataRows = 10
parser.MaxBufferSize = 4096
parser.MaxRows = 500
parser.TextQualifier = """"c
While parser.Read()
strID = parser("ID")
strName = parser("Name")
' Your code here ...
strStatus = parser("Status")
End While
End Using
' Or... programmatically setting up the parser for Fixed-width.
Using parser As New GenericParser()
parser.SetDataSource("MyData.txt")
parser.ColumnWidths = New Integer(3) {10, 10, 10, 10}
parser.SkipStartingDataRows = 10
parser.MaxRows = 500
While parser.Read()
strID = parser("ID")
strName = parser("Name")
' Your code here ...
strStatus = parser("Status")
End While
End Using
End Sub
End Class
There's also this from here, demonstrating DataTable usage:
Dim csv = "Name, Age" & vbCr & vbLf & "Ronnie, 30" & vbCr & vbLf & "Mark, 40" & vbCr & vbLf & "Ace, 50"
Dim reader As TextReader = New StringReader(csv)
Dim table = New DataTable()
Using it = reader.ReadCsvWithHeader().GetEnumerator()
If Not it.MoveNext() Then
Return
End If
For Each k As var In it.Current.Keys
table.Columns.Add(k)
Next
Do
Dim row = table.NewRow()
For Each k As var In it.Current.Keys
row(k) = it.Current(k)
Next
table.Rows.Add(row)
Loop While it.MoveNext()
End Using
And this Q&A illustrates how to sort the DataTable by a given column.

Array Out of bounds error VB

Sorry for the terrible wording on my last question, I was half asleep and it was midnight. This time I'll try to be more clear.
I'm currently writing some code for a mini barcode scanner and stock manager program. I've got the input and everything sorted out, but there is a problem with my arrays.
I'm currently trying to extract the contents of the stock file and sort them out into product tables.
This is my current code for getting the data:
Using fs As StreamReader = New StreamReader("The File Path (Is private)")
Dim line As String = "ERROR"
line = fs.ReadLine()
While line <> Nothing
Dim pos As Integer = 0
Dim split(3) As String
pos = products.Length
split = line.Split("|")
productCodes(productCodes.Length) = split(0)
products(products.Length, 0) = split(1)
products(products.Length, 1) = split(2)
products(products.Length, 2) = split(3)
line = fs.ReadLine()
End While
End Using
I have made sure that the file path does, in fact, go to the file. I have looked through debug to find that all the data is going through into my "split" table. The error throws as soon as I start trying to transfer the data.
This is where I declare the two tables being used:
Dim productCodes() As String = {}
Dim products(,) As Object = {}
Can somebody please explain why this is happening?
Thanks in advance
~Hydro
By declaring the arrays like you did:
Dim productCodes() As String = {}
Dim products(,) As Object = {}
You are assigning size 0 to all your arrays, so during your loop, it will eventually try to access a position that haven't been previously declared to the compiler. It is the same as declaring an array of size 10 Dim MyArray(10) and try to access the position 11 MyArray(11) = something.
You should either declare it with a proper size, or redim it during execution time:
Dim productCodes(10) As String
or
Dim productCodes() As String
Dim Products(,) As String
Dim Position as integer = 0
'code here
While line <> Nothing
Redim Preserve productCodes(Position)
Redim Preserve products(2,Position)
Dim split(3) As String
pos = products.Length
split = line.Split("|")
productCodes(Position) = split(0)
products(0,Position) = split(1)
products(1,Position) = split(2)
products(2,Position) = split(3)
line = fs.ReadLine()
Position+=1
End While

Index was outside the bounds of the array [VB.NET]

Hi i am new to VB and in the process of learning. This error occur sometimes and doesn't occur sometimes which i find it weird.
I receive the error Index was outside the bounds of the array, that points to Button30.Text = Split(newestversion, vbCrLf)(**1**)
My motive is to read line by line from a online hosted text file.
For example,
label1.text = line 1 of the text file
label2.text = line 2 of the text file
This is very much what i want.
Here is my current code (EDITED):
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("direct link to my online txt file")
Dim response As System.Net.HttpWebResponse = request.GetResponse
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream)
Dim stringReader As String
stringReader = sr.ReadLine()
Button10.Text = stringReader
Dim newestversion As String = sr.ReadToEnd
Dim currentversion As String = Application.ProductVersion
Dim part() As String = Split(newestversion, vbCrLf)
If part.Length < 10 Then
' not enough items in the array. You could also throw and exception or do some other stuff here
Label10.Text = "beta"
Exit Sub
End If
'updates new episode numbers on buttons
Button20.Text = part(0)
Button30.Text = part(1)
Button40.Text = part(2)
Button50.Text = part(3)
Button60.Text = part(4)
Button70.Text = part(5)
Button80.Text = part(6)
Button90.Text = part(7)
Button100.Text = part(8)
Button110.Text = part(9)
End If
Thank You!!
You split your String for line breaks. This gives you an array, having one entry for each line in the String. However, you do not check if this array holds the amount of items you expect. You could do:
Dim newestversion As String = sr.ReadToEnd
Dim currentversion As String = Application.ProductVersion
Dim part() As String = Split(newestversion, vbCrLf)
If part.Length < 10 Then
' not enough items in the array. You could also throw and exception or do some other stuff here
MsgBox(String.Format("Array only has {0} items", part.Length))
Exit Sub
End If
'updates new episode numbers on buttons
Button20.Text = part(0)
Button30.Text = part(1)
Button40.Text = part(2)
...
Edit for the updated question
If you do have a problem like this, just approach it systematically and get as much information as you can. First you have to check if you really get the data you want from the remote source. To do that, add some logging (e.g. a MsgBox(newestversion) or a real log file). Check if the data you get is what you expect. If not, there's already a problem with your request/response code, which is a completely different problem than what I provided a solution for. If newestversion is OK, check if the splitting works by printing out the part() array. Maybe the server uses a different operating system or just uses vbCr as newline and not vbCrlf. If the splitting also works, you are done.

How to dislay mismatch lines when comparing two text files?

I'm new to VB.Net. I've implemented scripting to compare two text files that checks if the value or data is different from each other. The only problem is it shows only one line instead of two
Below is the data that is in text A and C:
Text A: Orange,Apple,Mango,Strawberry,Banana
Text B: Orange, Apple, Mango, Blueberry, Grapes
Here is my script
Sub Main()
Const ForReading = 1
Dim objFile1, objFile2, objFile3
Dim objFSO = CreateObject("Scripting.FileSystemObject")
objFile1 = objFSO.OpenTextFile("C:\Scripts\A.txt", ForReading) 'Current.txt represents Text from AWS network
Dim strAddresses, strCurrent, strNoAddress
strAddresses = objFile1.ReadAll
objFile1.Close()
objFile2 = objFSO.OpenTextFile("C:\Scripts\C.txt", ForReading) 'Current.txt represents Text from Shell network
Do Until objFile2.AtEndOfStream
strCurrent = objFile2.ReadLine
If InStr(strAddresses, strCurrent) = 0 Then
strNoAddress = strCurrent & vbCrLf
End If
Loop
objFile2.Close()
objFile3 = objFSO.CreateTextFile("C:\Scripts\Differences.txt")
objFile3.WriteLine(strNoAddress)
objFile3.Close()
End Sub
Your code does not work because you overwrite strNoAddress everytime the if conditions is true:
strNoAddress = strCurrent & vbCrLf
So when you hit Blueberry, strNoAddress becomes Blueberry\n.
When you hit Grapes, strNoAddress becomes Grapes\n instead of Blueberry\nGrapes\n.
You want to concatenate the strings instead:
strNoAddress &= strCurrent & vbCrLf
A more "up-to-date" version of your code without the legacy/leftover functions of VB6 could look like:
Dim addresses = File.ReadAllLines("C:\Scripts\A.txt")
Dim noAdress = String.Empty
Using reader = new StreamReader("C:\Scripts\B.txt")
Do Until reader.EndOfStream
Dim current = reader.ReadLine
If Not addresses.Contains(current) Then
noAdress &= current & Environment.NewLine
End If
Loop
End Using
...
Or, to make it even more simple (good enough for small files, and without a trainling newline):
Dim fileA = File.ReadAllLines("C:\Scripts\A.txt")
Dim fileB = File.ReadAllLines("C:\Scripts\B.txt")
Dim noAdress = String.Join(Environment.NewLine, fileB.Where(Function(b) Not fileA.Contains(b)))