How to add variables together without them bunching up? - vb.net-2010

I have a program with the following code:
Dim Var1 as string = textbox1.text
Dim Var2 as string = textbox2.text
Dim Var3 as string = textbox3.text
Dim EndVar as string = Var1 + Var2 + Var3
Lets assume the user enters 1, 2, and 3 for the three textbox variables, I want EndVar to equal 6, but it gives me 123. How do I get it to give me 6?

you can convert each of them to int,sum them and then convert it back to string:
Dim EndVar as string = (Convert.toInt32(Var1) + Convert.toInt32(Var2) + Convert.toInt32(Var3)).ToString();

System.Convert.To ... whatever you need...
Check out this http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
Dim values() As String = { "One", "1.34e28", "-26.87", "-18", "-6.00", _
" 0", "137", "1601.9", Int32.MaxValue.ToString() }
Dim result As Integer
For Each value As String In values
Try
result = Convert.ToInt32(value)
Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", _
value.GetType().Name, value, result.GetType().Name, result)
Catch e As OverflowException
Console.WriteLine("{0} is outside the range of the Int32 type.", value)
Catch e As FormatException
Console.WriteLine("The {0} value '{1}' is not in a recognizable format.", _
value.GetType().Name, value)
End Try
Next
' The example displays the following output:
' The String value 'One' is not in a recognizable format.
' The String value '1.34e28' is not in a recognizable format.
' The String value '-26.87' is not in a recognizable format.
' Converted the String value '-18' to the Int32 value -18.
' The String value '-6.00' is not in a recognizable format.
' Converted the String value ' 0' to the Int32 value 0.
' Converted the String value '137' to the Int32 value 137.
' The String value '1601.9' is not in a recognizable format.
' Converted the String value '2147483647' to the Int32 value 2147483647.

Related

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

Input string was not in a correct format while adding string to integer

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

Vb.net - Split String and convert to DateTime

I have 1 datagridview named IncomingMailDGV.
Sample data on Contents Column:
R-1 temperature (6.25) rose above high bound SLTCR at Warehouse-1 at 27/07/15 13:40
R-2 temperature (6.62) rose above high bound SLTCR at Store at 27/07/15 13:42
R-3 temperature (6.31) rose above high bound SLTCR at Warehouse-2 at 27/07/15 13:45
Note: Some contents has three spaces on the last part of the message.
I want to get the date and time which is placed on the last part and convert it to this format: "M/dd/yyyy HH:mm tt"
I'm using below code but its not working:
Sub FilterAlert()
Try
Dim Dbcon As New OleDbConnection(connStr)
Dbcon.Open()
For x As Integer = 0 To IncomingMailDGV.Rows.Count - 1
Dim line2 As String = IncomingMailDGV.Rows(x).Cells("Contents").Value.ToString
Dim separators() As String = {",", " ", "(", ")"}
Dim length As Integer = line2.Length
Dim alertdatetime As String
Dim alertdate_time As String
data2 = line2.Split(separators, StringSplitOptions.RemoveEmptyEntries)
alertdate_time = line2.Substring(length - 14, 14)
Dim alertstring = alertdate_time.Split(separators, StringSplitOptions.RemoveEmptyEntries)
alertdatetime = alertstring(0)
alertdatetime = DateTime.ParseExact(alertdatetime, "dd/MM/yyHH:mm", Nothing)
console.writeline (alertdatetime)
Next
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Update: Some cells on Contents Column are empty.
If you mean that there may be more than one space between the date and the time, then you can just take the last 14 characters from the string. The following code assumes that the date and time are always preceded by " at ". It's not clear what you want to do if the string is not in the correct format, this code simply ignores invalid strings.
Note that DateTime doesn't have a format, it's just numbers. You can use DateTime.ToString to output the date and time in whatever format you want.
This code is intended to replace everything inside the For loop.
Dim line2 As String = IncomingMailDGV.Rows(x).Cells("Contents").Value.ToString
Dim pos As Integer = line2.LastIndexOf(" at ")
If pos < 0 Then Continue For
Dim alertstring() As String = line2.Substring(pos + 4).Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
If alertstring.length <> 2 Then Continue For
Dim alertdatetime As DateTime
If Not DateTime.TryParseExact(alertstring(0) & alertstring(1), "dd/MM/yyHH:mm", _
System.Globalization.CultureInfo.InvariantCulture, Nothing, alertdatetime) Then Continue For
Console.WriteLine(alertdatetime.ToString("M/dd/yyyy HH:mm tt"))

How can I Parse text document in VB,Net for values?

I'm looking to parse this text file into strings to insert them into a database.
Source Text File gets read as the following string:
Line of unwanted text
Another line of unwanted data
Timestamp: 1/1/10 12:00 PM
ID: 1
Details: All data processed. Length will vary.
I'd like to just read Timestamp, ID and Details and place them into separate strings to insert them into a data table. What is the best method of capturing everything after the : and to the end of the line?
Dim Details as String = TextFile.Substring(Message.IndexOf("Details:"), X)
If you have to use a String as input, you can use String.Split to break it up into lines, and process each line. String.Substring can be used to extract the rest of the line - I've just hardcoded the starting positions below.
Dim timestamp As String = Nothing
Dim id As String = Nothing
Dim details As String = Nothing
For Each line In input.Split({vbCrLf, vbCr, vbLf}, StringSplitOptions.None)
If line.StartsWith("timestamp:", StringComparison.OrdinalIgnoreCase) Then
timestamp = line.Substring(10).Trim()
ElseIf line.StartsWith("id:", StringComparison.OrdinalIgnoreCase) Then
id = line.Substring(3).Trim()
ElseIf line.StartsWith("details:", StringComparison.OrdinalIgnoreCase) Then
details = line.Substring(8).Trim()
End If
Next
If you can change how you read the data, then the loop could just be:
For each line In File.ReadLines("your\file\name.txt")
...
Next
Assuming your files are flawless... One way to do it :
Imports System.IO
Dim AllLines() As String = File.ReadAllLines(FilePath)
Dim DatasIndex As Int32 = -1
For i As Int32 = 0 To AllLines.Length - 1
If AllLines(i).StartsWith("T") OrElse AllLines(i).StartsWith("t") Then
If AllLines(i).ToUpper().StartsWith("TIMESTAMP: ") Then
DatasIndex = i
Exit For
End If
End If
Next
If DatasIndex > -1 Then
' Dim ReadDate As Date = Date.Parse(AllLines(DatasIndex).Substring(11))
' Dim ReadID As Int32 = Integer.Parse(AllLines(DatasIndex + 1).Substring(4))
Dim ReadDate As String = AllLines(DatasIndex).Substring(11)
Dim ReadID As String = AllLines(DatasIndex + 1).Substring(4)
Dim ReadDetails As String = AllLines(DatasIndex + 2).Substring(9)
' send to database
End If
You didn't tell if Timestamp: , ID: and Details: Strings are always in the same order and has a trailing space after each property name.

Converting a binary value from the registry to a string in VB 2010

I am trying to pull a value from the registry that is in binary format and converting it into a string and entering it into a text box. When I run my code the text box is empty. I have checked the registry and there is a binary value there as well as checking with code in VB. Below is my code for getting the value and converting it and adding it to a text box.
Dim LANDeskVirus As String = CStr(My.Computer.Registry.GetValue _
("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\LANDesk\ManagementSuite\WinClient\Antivirus", _
"PatternFileDate", Nothing))
Dim LANDeskVirusDefintion As String = Convert.ToString(LANDeskVirus)
Dim BinaryText As String = LANDeskVirusDefintion
Dim Characters As String = Regex.Replace(BinaryText, "[^01]", "")
Dim ByteArray((Characters.Length / 8) - 1) As Byte
For Index As Integer = 0 To ByteArray.Length - 1
ByteArray(Index) = Convert.ToByte(Characters.Substring(Index * 8, 8), 2)
Next
TextBox1.Text = (ASCIIEncoding.ASCII.GetString(ByteArray))
Look at the registry with Regedt32.exe. If the Type of that key value is REG_SZ, then it is a string and you can just assign it to the text box directly.
TextBox1.Text = My.Computer.Registry.GetValue _
("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\LANDesk\ManagementSuite\WinClient\Antivirus", _
"PatternFileDate", Nothing)
If it is something like REG_DWORD, then you can convert it to a string and then assign it to the text box, something like this:
TextBox1.Text = CStr(My.Computer.Registry.GetValue _
("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\LANDesk\ManagementSuite\WinClient\Antivirus", _
"PatternFileDate", Nothing))
With a REG_BINARY value with 8 bytes, you can probably get the date like this. (You might need to use .FromBinary instead of .FromFileTime)
dim b() as byte
b = CStr(My.Computer.Registry.GetValue _
("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\LANDesk\ManagementSuite\WinClient\Antivirus", _
"PatternFileDate", Nothing))
TextBox1.Text = DateTime.FromFileTime(BitConverter.ToUInt64(b, 0)).ToString