VB windows form calculate the digit in a multiline textbox - vb.net

I want to calculate each line: it's like first line 123*1.616 and the second line 213*1.616, and display each total.
Every number entred in the kilogram textbox will mutiply 1.616 and then show the result in the kati label.
Here is my code:
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Enter
For Each digit In (TextBox1.Text)
total1 = Val(digit) * 1.616
Label9.Text = total1
Next
Label9.Text = total1
End sub
Please help me find some solution or explanation to achieve the output.

This should work
Private FACTOR As Decimal = 1.616
Private SEPARATOR As String = Environment.NewLine
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Click
Label9.Text = TextBox1.Text.
Split({SEPARATOR}, StringSplitOptions.RemoveEmptyEntries).
Select(Function(s1) $"{Decimal.Parse(s1) * FACTOR:0.00#}").
Aggregate(Function(s1, s2) $"{s1}{SEPARATOR}{s2}")
End Sub
Here are the functions in the LINQ
Split makes an array out of each line in the TextBox using SEPARATOR as the delimiter
Select transforms the elements into their value times FACTOR
Aggregate puts the elements back together into a SEPERATOR delimited string
Why didn't your original code work?
You were iterating over each char in the text, and multiplying the char by a float (Option Strict On, as suggested in the comments would have prevented that).
Then in each iteration, you do (simplified) Label9.Text = Val(digit) * 1.616 which overwrites the Label every time.
If you were to step through in debug (also suggested in comments), you would see the Label becoming 1x1.616=1.616, 2x1.616=3.232, 3x1.616=4.848, etc. The result was the very last character in your TextBox, '3', times 1.161 = 4.848. Obviously, this was not what you wanted. You needed to instead iterate over each entire number. The multiline TextBox separates each line with a new line. So we iterate over each line instead.

you can use split string by vbCrLf
Sub main()
Dim multilinetext As String =
"10
20
30
40
50
60"
Dim number_array = multilinetext.Split(vbCrLf)
Dim output As Integer = 0
For Each i In number_array
output += i
Next
Stop
End Sub

Related

How can calculate the number of columns in a textfile and show in a textbox, in vb.net?

I have a textfile (data.txt) with 3 columns, each column with one variable (x1, x2 and x3). I would like to calculate a number of columns and show in a specific textbox (like textbox1).
For example. My data.txt:
x1 x2 x3
10 15 20
20 10 10
TextBox1 needs to show: 3
Text files don't have columns. What you have is a file where each line separates elements by a space and each row is separated by a CR/LF (carraige return/line feed) To work with the text file put
Imports System.IO
at the top of the code file.
I am guessing that you will want to do more with the file than just determin the number of "columns" so, we will read the entire file. File.ReadAllLines() returns an array of lines in the file.
We take the first line in the file (index 0) and split it by a space. The lowere case c followint " " tells the compiler that you mean a Char not a String. Then we take the Length of the resulting array to find the number of columns.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines = File.ReadAllLines("C:\Users\******\Desktop\Code\OPdata.txt")
Dim NoOfColumns = lines(0).Split(" "c).Length
TextBox1.Text = NoOfColumns.ToString
'Some other things you can do
Dim dt As New DataTable
Dim columns = lines(0).Split(" "c)
dt.Columns.Add(columns(0), GetType(Integer))
dt.Columns.Add(columns(1), GetType(Integer))
dt.Columns.Add(columns(2), GetType(Integer))
For index = 1 To lines.Length - 1
Dim values = lines(index).Split(" "c)
dt.Rows.Add({values(0), values(1), values(2)})
Next
DataGridView1.DataSource = dt
End Sub
You might want to consider using Microsoft.VisualBasic.FileIO.TextFieldParser. It's designed to process structured text files (either delimited or fixed-width) and will remove some of the necessary ceremony compared with direct file I/O as in Mary's answer. Note that TextFieldParser implements IDisposable, so it should either be used within a Using block or disposed manually.
FileOpen(1, "data.txt", OpenMode.Input)
line1$ = LineInput(1) 'get first line
FileClose(1)
TextBox1.Text = UBound(Split(line1, " ")) + 1

Read every fourth line from a text file

So, I have a text file with the following:
Andrew Law
0276376352
13 Parsons St
Kevin Kyle
0376458374
29 Penrod Drive
Billy Madison
06756355
16 Stafford Street
Now on my Form, I have a ListBox. When the Form loads, I would like to read every fourth line from the text file (every name) and display it in the ListBox.
All I have right now is the following:
Dim People As String
People = System.IO.File.ReadAllLines("filelocation")(3)
ListBox1.Items.Add(People)
This however only reads line number 4 where as I want to read EVERY fourth line after that also.
Add all the strings extracted from a source file, when the current line is a multiple of a pre-defined number of lines to skip or 0, to a ListBox and allow a user to select a Name from the list to fill some Labels with the details related to the selected Name.
Parse and extract the People Names from the array of string. Each Name can be found at an index which is multiple of the value specified by the skipLines field.
Add each Name to a ListBox control.
When a Name is selected from the ListBox list of names, add the related details to some Labels (named lblPhoneNumber and lblAddress here). To identify the correct informations in the array, we're using the skipLines value as a multiplier this time. This way, even if you add some more details in the list of names, you'll find the right informations modifying just the skipLines value.
You need to subscribe to the SelectedIndexChanged event of the ListBox:
Public Class Form1
Private people As String()
Private skipLines As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
skipLines = 3
people = File.ReadAllLines([Source File])
For line As Integer = 0 To people.Length - 1
If line Mod skipLines = 0 Then
ListBox1.Items.Add(people(line))
End If
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim StartIndex As Integer = ListBox1.SelectedIndex * skipLines
lblPhoneNumber.Text = people(StartIndex + 1)
lblAddress.Text = people(StartIndex + 2)
End Sub
End Class
How this works:
Define the number of lines to skip. We want a line of text, then skip 3 lines, here:
Dim skipLines As Integer = 3
We create an array of strings. It will contain the output of File.ReadAllLines(), which of course returns an array of strings:
Dim people As String() = File.ReadAllLines([Source File])
Iterate the whole content of the array of strings, line by line. A collection enumeration starts from 0, so we parse the list from 0 to the number of elements - 1:
For line As Integer = 0 To people.Length - 1
'[...]
Next
The If condition if met when the current line number is a multiple of skipLines.
The Mod operator divides two numbers and returns the remainder of the operation. If there's no reminder, the line number is a multiple of skipLines, the number of lines we want to skip.
If line Mod skipLines = 0 Then
`[...]
End If
Finally, when the condition is met, add the content of the array of strings (the people array) at the index represented by the current line value, to the ListBox.Items collection:
ListBox1.Items.Add(people(line))

How to read an input from a barcode scanner and display into a TextBox?

First barcode content will be: 1|123456|ABC
Second barcode content will be: 2|123456789542|ABCDSE
I just want to retrieve the bold part.
Here's my code:
Private Sub TextScanPartNo_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextScanPartNo.KeyPress
TextVendorID.CharacterCasing = CharacterCasing.Upper
If Me.TextVendorID.Focused = False Then
TextVendorID.Focus()
TextVendorID.Text = e.KeyChar.ToString
e.Handled = True
End If
End Sub
If the input is always going to be xxx|xxxxxx|xxx then this is quite easily done. We can use the String.Split method:
Dim textToSplit As String = "1|123456|abc"
Dim text As String = textToSplit.Split(New Char() {"|"c})(1)
Note the use of (1) at the end of .Split(). .Split() returns a String() which results in the following output:
(0) 1
(1) 123456
(2) abc
Since you only want 123456 we can target this by appending (1) to the end of the .Split method.
Output of text is:
123456
Edited as OP has stated they are having problems with input "2|123456789542|ABCDSE". The format still stands as being xxx|xxxxxx|xxx so the Split() code will still work.
This is a screenshot of the code showing the output you are after:
You can use the split function:
Dim str() As String
str = Split(barcodeText, "|")
MsgBox("Your barcode is : " & str(1))

VB.NET - How to format text boxes so they divide the text into chunks of n letters?

I have two text boxes, that can only contain capital letters, and a variable where I store an unsigned integer. Let's say for instance 5. How can I make it so that my TextBoxes that contain random text are split into groups of 5 letter?
For example: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Becomes: ABCDE FGHIJ KLMNO PQRST UVWXY Z
I need this to be done in real time in case the text is replaced by the user. I also cannot use multiple text boxes that allow n characters each as the text I'm supposed to format can be indefinitely long.
You can use this approach for every time the Textbox.Text changes:
Private Sub Textbox1_TextChanged(sender As Object, e As EventArgs) Handles Textbox1.TextChanged
Dim sentence As String = Textbox1.Text
Dim pairedChars as Integer = 5
If pairedChars <= sentence.Length Then
'First remove all spaces from the last time
sentence.Replace(" ", "")
'Add spaces at every 5th place in the string
For i = 1 to (sentence.Length) / pairedChars
sentence = sentence.Insert(i * pairedChars + (i - 1), " ")
Next
End If
End Sub

Find missing value in a numbers sequence - DGV column

I tried searching and didn't have any success in fixing my problem so I tried finding my own solution.
First I found max (Max) value (min value is always 1), then I set loop to search value by value, but something is wrong with my loop.
For i As Integer = 1 To Max
For y As Integer = 0 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(y).Cells(0).Value = i Then
Else
builder2.Append(i & ",")
End If
Next
Next
To me loop looks OK but it's not working. If value i is found do nothing if it's not found add i to stringbuilder, and so on until it reaches Max value. But whatever combination I've tried I get some weird results.
Numbers are sorted from lowest to highest.
I've also extracted all values from DGV column to comma delimited string if it's easier that way...
EDIT :
Just for experimenting with that loop I've put i = 40 to 50 (to reduce the range). I know that missing values in DGV column are 40-46 and 59.
This is what I've got with loop above :
You can use LINQ to find missing numbers quite easily. You just need to get the existing numbers into a List, and then you can use Max() to find the largest number, and Except() to find the missing ones.
I put a DGV named DataGridView1 with one column, a button named bnPopulateDGV, and a button named bnFindMissingNumbers on a new Windows Form, and used the following code (with Option Infer On):
Private Sub bnPopulateDGV_Click(sender As Object, e As EventArgs) Handles bnPopulateDGV.Click
DataGridView1.Rows.Clear()
Dim seq1 = Enumerable.Range(1, 100).ToList()
Dim rand As New Random
' knock some out
For i = 1 To 5
seq1.RemoveAt(rand.Next(0, 50))
Next
For Each s In seq1
DataGridView1.Rows.Add(New String() {s.ToString()})
Next
End Sub
Private Sub bnFindMissingNumbers_Click(sender As Object, e As EventArgs) Handles bnFindMissingNumbers.Click
Dim existingNumbers As New List(Of Integer)
For Each r As DataGridViewRow In DataGridView1.Rows
existingNumbers.Add(CInt(r.Cells(0).Value))
Next
Dim min = 1
Dim max = existingNumbers.Max()
Dim missingNumbers = Enumerable.Range(min, max - min + 1).Except(existingNumbers)
MsgBox("Missing: " & String.Join(", ", missingNumbers))
End Sub