Input string was not in a correct format while adding string to integer - vb.net

I have a code like this :
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
i = (Integer.Parse(strarr(0)) + 1)
mincatval = i
my dr(1) value is L1 i want to add 1,so i want the out put L2,but i am getting error like this :Input string was not in a correct format.

Supposing that strarr(0) is the word "L1" and you want it to become "L2" then you need to isolate the numeric part from the text part and then rebuild the string taking the first part of strarr and the incremented value
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
Dim itShouldBeAnumber = strarr(0).Substring(1)
if Int32.TryParse(itShouldBeAnumber, i) Then
mincatval = strarr(0).Substring(0,1) & (i + 1)
else
MessageBox.Show("Not a valid number from position 1 of " & strarr(0))
End if
Of course this solution assumes that your string is Always composed of an initial letter followed by a numeric value that could be interpreted as an integer

Related

What is the simplest way to get the second item of each row in a string file

I have a String file with 8 items (separated by commas) in each row, e.g., CA,23456,aName,aType,anotherName,aWord,secondword,number. I want to create a new string of items consisting of the 2nd item (an Integer) of each row of the original file. I know there are many ways to do this but someone out there knows how to do it with very few lines of code, which is what I am looking for. I prefer not to use a parser.
The way to show what I have tried is to look at the code below.
Dim sn2 As String = ""
Dim sn2S As String = ""
Using readFile As New StreamReader(newFile1)
Do While readFile.Peek() <> -1
sn2S = readFile.ReadLine(1)
sn2 = sn2 & sn2S & ","
Loop
End Using
The code returns the second character of each row not the second item. What I hope to get is a string that looks like: 123,1345,4325,3321,3456,3211 etc. Where each number is the second item in each row of the original file.
You could split it up by cells
Dim row As String = "CA,23456,aName,aType,anotherName,aWord,secondword,number"
Dim cells() As String = row.Split(",")
Dim cellValue As String = cells(1)
But in your case, I would just do a search and Substring by the index of the delimiter.
Dim startPosition As Integer = row.IndexOf(",") + 1
Dim endPosition As Integer = row.IndexOf(",", startPosition)
Dim cellValue As String = row.Substring(startPosition, endPosition - startPosition)
If you have the whole file in memory, there could be some regex that could do the job with one pass.
As for this line
sn2 = sn2 & sn2S & ","
You might want to check at doing a join or using stringbuilder.
You could try
Dim sn2 As String = ""
Dim sn2S(7) As String = ""
Using readFile As New StreamReader(newFile1)
Do While readFile.Peek() <> -1
Array.Clear(sn25,0,sn25.Length)
sn2S = readFile.ReadLine(1).Split(",")
sn2 = sn2 & sn2S(1) & ","
Loop
End Using
In one line
Dim sn2 = String.Join(",", File.ReadAllLines(newFile1).Select(Function(s) s.Split(","c)(1)))
From the inside-out:
File.ReadAllLines(newFile1) splits the file into lines and results in a string array holding those lines, which is fed into...
...Select(Function(s) s.Split(","c)(1)) which operates on each line by splitting the line by comma s.Split(","c) and then indexing the resulting array (1) to return the second (zero-based) element. This is fed into...
String.Join(",", ... ) which takes those second elements and joins then together with comma.

Parsing numbers containing commas or periods

I have three values which need to be sorted from highest to lowest value. I use the following code which works like a charm until I want to use periods "." and commas ",". If I type "1,3" it displays as I like, but if I type "1.3" it changes to 13. My end users need to be able to use both commas and periods.
How can I fix this?
Dim IntArr(2) As Decimal
IntArr(0) = TextBox1.Text
IntArr(1) = TextBox2.Text
IntArr(2) = TextBox3.Text
Array.Sort(IntArr)
Dim highestNum As Decimal
Dim Midelnum As Decimal
Dim lowestNum As Decimal
lowestNum = IntArr(0)
Midelnum = IntArr(1)
highestNum = IntArr(2)
MsgBox("Highest " & highestNum)
MsgBox("lowest " & lowestNum)
MsgBox("middel " & Midelnum)
The problem is that it's based on culture. I say this because if I enter numbers as you described, I get the opposite effect ("1,3" -> "13", etc).
Here's a quick way to change the values to match the current culture.
At the top of your class, put this:
Imports System.Globalization
Then, you can do this:
Dim IntArr(2) As Decimal
Dim nfi As NumberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
Dim sep1 As String = nfi.NumberDecimalSeparator
Dim sep2 As String = If(sep1.Equals("."), ",", ".")
Dim useComma As Boolean = (TextBox1.Text.Contains(",") Or TextBox2.Text.Contains(",") Or TextBox3.Text.Contains(","))
'Replace the separator to match the current culture for parsing
Decimal.TryParse(TextBox1.Text.Replace(sep2, sep1), IntArr(0))
Decimal.TryParse(TextBox2.Text.Replace(sep2, sep1), IntArr(1))
Decimal.TryParse(TextBox3.Text.Replace(sep2, sep1), IntArr(2))
Array.Sort(IntArr)
sep1 = If(useComma, ",", ".")
sep2 = If(useComma, ".", ",")
'Reformat the results to match the user's input
Dim lowestNum As String = IntArr(0).ToString().Replace(sep2, sep1)
Dim middleNum As String = IntArr(1).ToString().Replace(sep2, sep1)
Dim highestNum As String = IntArr(2).ToString().Replace(sep2, sep1)
Dim msg As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
msg = String.Format(msg, highestNum, lowestNum, middleNum)
MessageBox.Show(msg)
Also, since you are using .NET, you may want to skip the VB6 way of doing things. Refer to my example to see what I've used.
You could use the hack of altering the string before saving it:
TextBox.Text.Replace(".",",")
But if you want to show the original input you could have a variable to detect the entered character:
Dim isDot As Boolean = False
Dim number As String = TextBox.Text
If number.Contains(".") Then
isDot = True
End If
And in the end replace it just for purposes of displaying
If isDot Then
number.Replace(",",".")
End If
The accepted answer uses too much unnecessary string manipulation. You can use the CultureInfo object to get what you need:
Sub Main
Dim DecArr(2) As Decimal
'Select the input culture (German in this case)
Dim inputCulture As CultureInfo = CultureInfo.GetCultureInfo("de-DE")
Dim text1 As String = "1,2"
Dim text2 As String = "5,8"
Dim text3 As String = "4,567"
'Use the input culture to parse the strings.
'Side Note: It is best practice to check the return value from TryParse
' to make sure the parsing actually succeeded.
Decimal.TryParse(text1, NumberStyles.Number, inputCulture, DecArr(0))
Decimal.TryParse(text2, NumberStyles.Number, inputCulture, DecArr(1))
Decimal.TryParse(text3, NumberStyles.Number, inputCulture, DecArr(2))
Array.Sort(DecArr)
Dim format As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
'Select the output culture (US english in this case)
Dim ouputCulture As CultureInfo = CultureInfo.GetCultureInfo("en-US")
Dim msg As String = String.Format(ouputCulture, format, DecArr(2), DecArr(1), DecArr(0))
Console.WriteLine(msg)
End Sub
This code outputs:
Highest: 5.8
Lowest: 4.567
Middle: 1.2

Concatenating three strings to create one string

I've been working on this assignment for class but ran into an issue when creating a string from three other strings. It creates a invoice number based on the first letter in the first and last name and the last 3 numbers of the zip code.
Dim split As String() = txtName.Text.Split(", ")
Dim last As String = split(0)
Dim first As String = split(1)
Dim invFirst = first.Substring(0, 1)
Dim invLast = last.Substring(0, 1)
Dim invZip = cityState.Substring(cityState.Length - 3)
Dim invNumber = invFirst + invLast + invZip
lstInvoice.Items.Add("Invoice Number: " + invNumber)
Instead of printing out AB123 it will print out just B123. I have tried using + and & and even tired converting all components to a string just to be sure it wasn't trying to treat the values as numbers or something.
Am I missing something like flushing the stream or casting them differently?
Split() returns an array. https://msdn.microsoft.com/library/tabh47cf(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
So you need to trim the strings. And then it will work.
https://dotnetfiddle.net/U5gvh5
Dim split As String() = txtName.Split(",")
Dim last As String = split(0).Trim()
Dim first As String = split(1).Trim()

How to extract the message exactly in vb.net

Below is my textbox which i store the output of my serial
Below is where i put the message inside the DataGridView the problem lies here see the last row of the grid there is an OK text.
my last photo shows the value of my line of text.
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile() As String
LineOfText = tt.Text
aryTextFile = Split(LineOfText, "+CMGL", , CompareMethod.Text)
dgv.Rows.Clear()
For i = 1 To UBound(aryTextFile)
'**********************
Dim LineOfTexts As String
Dim aryTextFiles() As String
LineOfTexts = aryTextFile(i)
aryTextFiles = Split(LineOfTexts, """", , CompareMethod.Text)
aryTextFiles(5) = aryTextFiles(5).Substring(0, 17).Replace(",", "-")
dgv.Rows.Add(New String() {aryTextFiles(3), aryTextFiles(6), aryTextFiles(5)})
Next i
is there any other way to extract the message exactly?
aryTextFiles(3) is the phone number/Sender aryTextFiles(6) is the message and aryTextFiles(5) is the date and time.
You can remove the last word by using Trim()
LineOfText = tt.Text.Substring(0, tt.Text.LastIndexOf(vbCrLf) - 3).Trim()
I used -3 to trim the last 3 characters.

How to check what sub-string follows follows a string matched by InStr

I am trying to use the function InStr to find a specific string in another string.
When I find it, I would like to check what directly follows this string (for example End-user) and return this portion. So far I Have managed to write this:
If InStr(LCase(analysis), "End-user:") > 1 Then Range("AE" & i).Value = "OK"
which marks the relevant cell as OK once this string has been detected.
Could anyone help me please?
InStr returns the first index of the string to search ("End-user:") into the target string (Analysis). You should take it, together with the lengths to calculate the substring you want. Also bear in mind that you are using LCase in one part but not in the other one (what provokes that the string to search will never be found as far as it contains a capital letter). A code delivering what you want:
Dim analysis As String : analysis = "End-user: anyone"
Dim stringToSearch as String : stringToSearch = "End-user:"
Dim finalBit As String
Dim startIndex As Integer: startIndex = InStr(LCase(analysis), LCase(stringToSearch))
If (startIndex > 0 And InStr(LCase(analysis), LCase(stringToSearch)) < Len(analysis)) Then
Dim endIndex As Integer: endIndex = startIndex + Len(stringToSearch)
finalBit = Mid(analysis, endIndex, Len(analysis) - endIndex + 1)
End If
'finalBit -> " anyone"
More directly:
Dim StrMain As String
Dim StrSearch As String
Dim LngPos As Long
StrMain = "sample text End-user:kilroy"
StrSearch = "End-user:"
LngPos = InStr(StrMain, StrSearch)
If LngPos > 0 Then MsgBox Right$(StrMain, Len(StrMain) - LngPos - Len(StrSearch) + 1)