Add TextBox strings as numbers - vb.net

I'm making a counter that updates when the calculate button is pressed, but when I press it it add it like:
11111
where the answer should be 5.
Const tax = 1.05
Dim capPrice = 4.0
Dim espPrice = 2.5
Dim latPrice = 3.5
Dim icedPrice = 3.0
'keeping here teporarily
Dim takeAway = True
If (takeAway = True) Then
capCounter.text = capCounter.text + capAmount.text
espCounter.Text = espCounter.Text + espAmount.Text
latCounter.Text = latCounter.Text + latAmount.Text
icedCounter.Text = icedCounter.Text + icedAmount.Text

What you observe is string concatenation because a TextBox stores strings. You have to convert it to a number, for example with Int32.Parse, then you can sum the values:
Dim capCount As Int32
Dim capAmount as Int32
Dim validCapCount = Int32.TryParse(capCounter.Text, capCount)
Dim validCapAmount = Int32.TryParse(capAmount.Text, capAmount)
If validCapCount AndAlso validCapAmount Then
capCounter.Text = (capCount + capAmount).ToString()
End If
' do the same with the other values ...

This is because the Property Text of a control is a String.
If you want to perform your addition, you must convert those texts to a Integer first :
capCounter.text = (CType(capCounter.text, Integer) + CType(capAmount.text, Integer)).ToString()
(This if you are sure it will only be integers contained in the texts)

If you will use it for numbers only and allow user imput I will recommend you to use a numericUpDown and not a textboxt.
Then you can use the Value property of the numericupdown and it will return a numeric value, not a String.
However, if you need it to be a textbox, use CType as SuperPeanut sugested or TryParse as Tim sugested

Most of the other comments explain most of it, but have you tried using a different type of control to display the information, perhaps a NumericUpDownControl?

Related

How to use substring() function to get middle string with relative index?

I want to extract characters from a string. However, the string doesn't have the same length every time.
Basically I get data from a database and I want extract the value I need in it. But I'm stuck on step where I have to extract the right value.
So first I get data like that :
infoDataset2 = accessRequet_odbc("select st_astext(st_snaptogrid(geom, 0.01)) from netgeo_point_tech", myConnection)
The result is something like : POINT(921021.98 6671778.45). What I need are the 2 figures, but their length is not fixed. I just want to remove POINT( and ).
Then I work on each line of the DataSet I get to cast each lines into a string with only the value needed.
For i = 0 To infoDataset2.Tables(0).Rows.Count - 1
geomPt = infoDataset2.Tables(0).Rows(i).ItemArray(0).Substring(geomPt = infoDataset2.Tables(0).Rows(i).ItemArray(0).Substring(1 + infoDataset2.Tables(0).Rows(i).ItemArray(0).LastIndexOf("(")))
Console.WriteLine(geomPt)
Next
This was my last try, where I was able to remove POINT( but I'm struggling with the length to cut ).
I want to learn from this, so, if possible, explain to me what I'm doing wrong here, or if my approach is lacking insight.
It will be horrible to debug that one long line. It makes no difference to the computer if you split it up into easy-readable parts. Here's some code to get the x- and y-coordinates from a string formatted as shown in the question:
Dim s = "POINT(921021.98 6671778.45)"
Dim b1 = s.IndexOf("("c) + 1
Dim b2 = s.IndexOf(")"c, b1) - 1
Dim parts = s.Substring(b1, b2 - b1 + 1).Split({" "c})
Dim x As Decimal = Decimal.Parse(parts(0))
Dim y As Decimal = Decimal.Parse(parts(1))
Another way of parsing the string is to use a regular expression, which can be more flexible. In this example, I used named capture groups to make it easy to see which parts are for the x and y:
Dim s = "POINT(921021.98 6671778.45)"
Dim x As Decimal
Dim y As Decimal
Dim re = New Regex("\((?<x>[0-9-.]+) (?<y>[0-9-.]+)\)")
Dim m = re.Match(s)
If m.Success Then
x = Decimal.Parse(m.Groups("x").Value)
y = Decimal.Parse(m.Groups("y").Value)
Else
' Could not parse point. Do something about it if required.
End If
Andrew Morton has given a nice answer, i upvoted that one, if you need an even easier way and that was still complicated use this
Dim s = "POINT(921021.98 6671778.45)"
Dim part1 As String = s.Remove(0, 6)
Dim part2 As String = part1.Substring(0, part1.Length - 1)
Dim split() As String = part2.Split(" ")
Dim x = split(0)
Dim y = split(1)
Here is an even probably easier to understand solution:
Dim s as String = "POINT(921021.98 6671778.45)"
Dim coordinate() as String = s.Replace("POINT(", "").Replace(")", "").Split(" ")
Enjoy!

How to convert textbox year date value to check if it has only 2 digits?

The problem that I have is related to only being possible to insert 2 digit's on the field year and I was wondering if it was possible to have a string with a value 2017 and only inserting 17 when I press a button.
I have tried to use the CONTAINS property to check if it only has numbers, but now I'm kind of stuck.
You could use regex.
Private Function returnLastTwo(input As Integer) As Integer
Dim matchYearString As String = "(?:(\d\d)(?:(\d\d))?)"
Dim output As Integer
If CStr(input).Length = 4 Then
output = Text.RegularExpressions.Regex.Match(CStr(input), matchYearString).Groups(2).Value
ElseIf CStr(input).Length = 2 Then
output = Text.RegularExpressions.Regex.Match(CStr(input), matchYearString).Groups(1).Value
Else
Throw New Exception("Check input")
End If
Return output
End Function
You can use a string/substring concept;
Module DateSplit
Sub Main()
Dim literal As String = "2017"
Dim substring As String = literal.Substring(2)
Console.WriteLine("Substring: {0}", substring)
End Sub
End Module
I did not test this code but should output 17
Another approach would be casting your date as a string and create a char array, then you can have access to the element and convert them back to numbers if you like
Dim dateToSplit As Integer = 2017
Dim strDate As String = dateToSplit.ToString()
Dim charArr() AS Char = strDate.ToCharArray()
Assuming your user enters a date like this: 01/01/2017, into the textbox:
dim dateFromTextbox = yourTextbox.Text ' ==> 01/01/2017
dim lastTwoDigits = Right(dateFromTextbox, 2) ' ==> 17

Convert String to integer and get null equal to 0

May I know got any simple way to perform this? It will hit an error when a.text is null. If I don't detect one by one, With a simple code may I convert a.text null to 0?
Dim count1 As Integer = 0
count1 = Convert.ToInt32(a.Text) + Convert.ToInt32(b.Text) + Convert.ToInt32(c.Text)
txt_display.Text = count1
Got any other method rather that I do like below detect one by one.
if a.Text = "" Then
a.Text = 0
End If
You have to detect one by one. Better way, will be to create your own function. Try below.
Dim count1 As Integer = 0
count1 = ConvertToInteger(a.Text) + ConvertToInteger(b.Text) + ConvertToInteger(c.Text)
txt_display.Text = count1
Private Function ConvertToInteger(ByRef value As String) As Integer
If String.IsNullOrEmpty(value) Then
value = "0"
End If
Return Convert.ToInt32(value)
End Function
If your objective is to sum the values in your textboxes and ignore the textboxes that cannot be converted to integers then you can simply use Int32.TryParse.
It will set your variable to 0 if the text cannot be converted to an integer without throwing exceptions.
' In place of your textboxes
Dim x1 As String = "2"
Dim x2 As String = Nothing
Dim x3 As String = "5"
Dim a, b, c As Integer
Int32.TryParse(x1, a)
Int32.TryParse(x2, b)
Int32.TryParse(x3, c)
Dim result = a + b + c
Console.WriteLine(result)
Instead, if you want to write the "0" string into the textbox text to signal your user of the wrong input, then you have to check the textboxes one by one, again using Int32.TryParse
Dim value1 as Integer
if Not Int32.TryParse(a.Text, value1) Then
a.Text = "0"
End If
' Here the variable value1 contains the converted value or zero.
' repeat for the other textboxes involved
A different approach using If Operator:
Dim count1 As Integer = 0
count1 = If(String.IsNullOrEmpty(a.Text), 0, Convert.ToInt32(a.Text)) + If(String.IsNullOrEmpty(b.Text), 0, Convert.ToInt32(b.Text)) + If(String.IsNullOrEmpty(c.Text), 0, Convert.ToInt32(c.Text))
txt_display.Text = count1
Example:
If String.IsNullOrEmpty(a.Text) Then
a.Text = "0"
End If
As per the Microsoft Documentation, a null string (Nothing) is different from an empty string (""):
The default value of String is Nothing (a null reference). Note that this is not the same as the empty string (value "").
You also use the = operator, which can be tricky with String types. For more info, see this post and the answer which was awarded a 50 points bounty.
If you use If with only two arguments, the following code
If a.Text Is Nothing Then
a.Text = 0
End If
Can be turned into a one-liner: Dim MyNumber as Integer = If(a.Text, 0)
If you meant to work with empty strings, then you can use: Dim MyNumber as Integer = If(a.Text.Length = 0, 0, a.Text).
If you want to deal with both, you can use String.IsNullOrEmpty(a.Text) as suggested by the currently accepted answer; or you can use a.Text="", a.Text = String.Empty, or a.Text = vbNullString, which are all equal (see the post I referred to earlier)
Finally, note that the conversion from a String type to an Integer type is made implicitly. There is no need to use the explicit cast conversions such as CType() or Convert.ToInt32.

VB.NET add a decimal Point to Series

The following Function creates multiple series for a graph.
Function createSeries(ByVal fileNames() As String, ByVal intValXAxis As Integer, ByVal intValYAxis As Integer) As Series()
Dim ChartSeries(fileNames.Count) As Series
Dim i As Integer = 0
For Each filename In fileNames
ChartSeries(i) = New Series
ChartSeries(i).ChartType = SeriesChartType.FastLine
ChartSeries(i).ChartArea = "ChartArea1"
If filename.Contains("NOK") = True Then
ChartSeries(i).Color = Color.Red
ChartSeries(i).BorderWidth = 3
Else
ChartSeries(i).Color = Color.Green
End If
Dim fileReader = My.Computer.FileSystem.OpenTextFileReader(filename)
Do
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
ChartSeries(i).Points.AddXY(strCache(intValXAxis - 1), strCache(intValYAxis - 1))
ChartSeries(i).ToolTip = filename
Loop Until fileReader.EndOfStream = True
i += 1
Next
Return ChartSeries
End Function
The problem I have is, that the Y-Values of the Series I create are mostly something like that: 0,09440104 or 0,1757813. I need these Values shown on the graph as they are, but the zero's got removed and the Y-Point-Values are : 9440104 or 1757813
I tried to format them with "Globalization" before adding them to the Series, but it doesn't solved the problem.
Just to be clear: I want the numbers as shown above(0,09440104 and 0,1757813) to be the Y-values of the points.
How can i solve the problem?
Thanks in advance.
By default, En-US culture will read your comma "," as thousand separator and thus taking your data as > 0 rather than < 0.
You have two options: change the culture or change the string format. If all your numbers are less than 1000 (or, to be more precise, not having . as thousand separator), I recommend simply to replace , with .
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
Dim repStrX = strCache(intValXAxis - 1).Replace(",",".")
Dim repStrY = strCache(intValYAxis - 1).Replace(",",".")
ChartSeries(i).Points.AddXY(repStrX , repStrY)
Or, if they are having value more than 1000 (or, again, to be more precise, not having . as thousand separator), without specifying the culture, you could also use Replace with some tricks: making use of non-existing character as intermediate value to flip between . and , in the original string.
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
Dim repStrX = strCache(intValXAxis - 1).Replace(",","G").Replace(".",",").Replace("G",".")
Dim repStrY = strCache(intValYAxis - 1).Replace(",","G").Replace(".",",").Replace("G",".")
ChartSeries(i).Points.AddXY(repStrX , repStrY)

Is possible to ignore the TextBox?

I'm creating a program to calculate the average. There are 12 TextBox and I want to create the possibility to leave some fields blank. Now there are only errors and the crash of the program. Is possible to create that?
This is part of code:
ItalianoScritto = (TextBox1.Text)
MatematicaScritto = (TextBox2.Text)
IngleseScritto = (TextBox3.Text)
InformaticaScritto = (TextBox4.Text)
ScienzeScritto = (TextBox5.Text)
FisicaScritto = (TextBox6.Text)
MediaScritto = (ItalianoScritto + MatematicaScritto + IngleseScritto + InformaticaScritto + ScienzeScritto + FisicaScritto) / 6
Label10.Text = Str(MediaScritto)
If i leave blank the textbox1 when I click on the button to calculate the average Vb says Cast not valid from the string "" to type 'Single' and the bar of te textbox1 become yellow
I would do the following:
Iterate over the textboxes and check if you can parse the value into an iteger. If yes, add it to a value list.
Then add all values from that list and divide it by the number of cases.
It is faster than big if-statements and resilient against error
dim TBList as new list(of Textbox)
'add your textboxes to the list here
TbList.add(Textbox1)
...
dim ValList as new List(Of Integer)
for each elem in Tblist
dim value as integer
If integer.tryparse(elem.text,value)=True
ValList.add(Value)
else
'report error or do nothing
end if
next
dim Result as Integer
Dim MaxVal as Integer =0
for each elem in ValList
Maxval +=elem
next
Result = MaxVal / ValList.count
If you need support for point values, just choose double or single instead of Integer.
Also: regardless what you do -CHECK if the values in the textboxes are numbers or not. If you omit the tryparse, somebody will enter "A" and your app will crash and burn
Also: You OPTION STRICT ON!
You just have to check if the TextBox is blank on each one before using the value:
If TextBox7.TextLength <> 0 Then
'Use the value inside
End If
The way to do it depends a lot of your code. You should consider editing your question giving more information (and code) in order to us to help you better.