Getting this error: "Conversion from string "" to type 'Double' is not valid." visual studio - vb.net

Im trying to make a app for cafe. It has a simple interface coffee names with labels and quantity with numericupdown, receipt textbox and receipt button. I coded receipt button to show coffee name and quantity in receipt textbox like this:
If (espresso.Value > 0) Then receipt.AppendText("Espresso" + vbTab + vbTab + espresso.Value.ToString + Environment.NewLine)
that works fine but i want to add the price next to quantity of the coffee so i added these lines :
Dim espressoprice As Double
espressoprice = 3
Dim espressoquantity As Double = Convert.ToDouble(espresso.Value)
Dim espressototal As Double
espressototal = (espressoprice * espressoquantity)
(espresso.value is numericupdown value)
and changed the first codeline like this:
If (espresso.Value > 0) Then receipt.AppendText("Espresso" + vbTab + vbTab + espresso.Value.ToString + vbTab + espressototal + Environment.NewLine)
but i keep getting this error:
"Espresso 2 " "Conversion from string "" to type 'Double' is not valid."
What am i doing wrong please help.

The proper solution to this problem is to use the correct operator. You are trying to perform string concatenation but you are using the addition operator. This:
"Espresso" + vbTab + vbTab + espresso.Value.ToString + vbTab + espressototal + Environment.NewLine
is actually performing multiple additions. Addition maps to concatenation for two Strings but for numbers, addition is mathematical, NOT textual. In order to add a String and a numeric value, the system has to implicitly convert one of them to the other type. You are obviously assuming that the number will be converted to a String but it's actually the opposite that is happening, i.e. the system is trying to convert a String to a number and it is failing. This is why you should not rely on implicit conversions. If you used the concatenation operator, as you should when performing concatenation, then there's only one way it can go:
"Espresso" & vbTab & vbTab & espresso.Value.ToString & vbTab & espressototal & Environment.NewLine
Notice that, in this case, you don't have to explicitly convert the number to a String because the concatenation operator is defined for Strings and numeric values. Concatenation is a String operation so you know for a fact that everything that can be treated as a String, will be.
That said, there are better options anyway, e.g.
receipt.AppendText(String.Concat("Espresso", vbTab, vbTab, espresso.Value, vbTab, espressototal, Environment.NewLine)

In your line where you added expressototal you need to convert its value to a string in order to add it to other strings, that is, expressototal.ToString.

Related

Inputbox is not accepting double number VBA excel

I have a declaration like number= InputBox("Number for:", "Number:"), number is declared as Dim number As Double but when I enter a double number, for example 5.4, into the Inputbox and transmit it into a cell, the cell shows me 54, it deletes the point.
How can I fix this?
THX
If you want to detect which settings your Excel uses for the Decimal seperator, try the code below:
MsgBox "Excel uses " & Chr(34) & Application.DecimalSeparator & Chr(34) & " as a decimal seperator"
if you want to change it to ., then use the line below:
Application.DecimalSeparator = "."
Unfortunately, VBA is horrible at handling differences in decimal seprators. In your case, you should probably use a comma (,), instead of a punctuation/dot (.).
Edit: Using the Application.DecimalSeparator method, it now works regardless of regional settings. Be aware though, it seems to cause some issues if you change the comma separator settings for Excel (it seems that VBA somewhat ignores this setting). If you do not change that however, the example should work in all other cas
Sub GetNumberFromInputBox()
Dim val As String
Dim num As Double
'Get input
val = InputBox("Number for:", "Number:")
Debug.Print Application.DecimalSeparator
If IsNumeric(val) Then
'Try to convert to double as usual
num = CDbl(val)
'If the dot is removed automatically, then
'you will se a difference in the length. In
'those cases, replace the dot with a comma,
'before converting to double
If Len(val) <> Len(num) Then
If Application.DecimalSeparator = "," Then
num = CDbl(Replace(val, ".", ","))
Else
num = CDbl(Replace(val, ",", "."))
End If
End If
'Pring the number
Debug.Print "You selected number: " & num
Else
'If its not a number at all, throw an error
Debug.Print "You typed " & val & ", which is not a number"
End If
End Sub

Visual Studio - CDbl to Double.TryParse when inputting to array

I'm finishing up a project and needed some clarification on a particular issue I'm running into.
Do While intCount < dblNumbers.Length AndAlso strInput <> String.Empty
dblNumbers(intCount) = CDbl(InputBox("Please enter number " & (intCount + 1) & "."))
intCount += 1
Loop
I'm running into issues changing that a to Double.TryParse for validating as opposed to the CDbl. Any of the ways I've entered it have caused the inputs to not store in the array. Thanks in advance.
TryParse doesn't return the converted value. It returns the validation result. You get the converted value from the parameter.
Dim number As Double
If Double.TryParse(InputBox("Please enter number " & (intCount + 1) & "."), number) Then
dblNumbers(intCount) = number
Else
'Invalid input.
End If

recordset.GetString in Access VBA Query returns an extra character after the result

I have a query that I execute through VBA in Access 2010. The result of the query should be AFR, but it returns AFR with an extra line below it. I have added the "'" character to make the extra line visible.
TempHold = rs.GetString
Debug.Print "'" & TempHold & "'"
Returns this:
'AFR
'
But should return this:
'AFR'
I have tried using the below code, but none of the If statements evaluate as True. The code should check for a " ", a vbNewLine, or vbCrLf character but none evaluate as true. Does anyone know of any additional characters that would result in a new line?
If Right(TempHold, 1) = " " Then
TempHold = Left(TempHold, Len(TempHold) - 1)
ElseIf Right(TempHold, 2) = vbNewLine Or Right(TempHold, 2) = vbCrLf Then
TempHold = Left(TempHold, Len(TempHold) - 2)
End If
Use:
Asc(Right(TempHold, 1))
to get the Ascii character code.
Once you've found the character code (which, as you wrote in your comment, was 13), you can use your code to remove it:
If Right(TempHold, 1) = Chr(13) Then
TempHold = Left(TempHold, Len(TempHold) - 1)
End If
In this case, you can also use vbCr, which is the same as Chr(13).
The best way to get rid of the carriage return in my opinion is to stop it being created in the first place. This method is a lot tidier than having to remove the last character.
In the .GetString method there is a parameter for RowDelimiter which by default is set to be a carriage return. However you can change this to be whatever you want including a zero length string as follows:
rs.GetString(, , , "")
If you run your debug again with this code:
rs.GetString(, , , "")
Debug.Print "'" & TempHold & "'"
You will get this result:
'AFR'
Remember if you want something different to be placed between rows then just change the zero length string to whatever you need.

ERR conversion from string to type 'double' is not valid. vb.net

I have a label name annual it display number from table in the database , this number is displayed like this 27.9828272.
I want just the 2 decimals.
I tried
If FrmLogin.CBformState.Text = "User" Then
com1.CommandText = "select * from balance where UserID = '" & FrmLogin.txtUserName.Text & "'"
com1.Connection = cn1
dr2 = com1.ExecuteReader
If dr2.Read Then
Dim b As Double
annual.Text = b
b = Math.Round(b, 2)
FirstName.Text = "'" & LCase(dr2(0)).ToString() & "'"
sick.Text = "'" & LCase(dr2(1)).ToString() & "'"
Maternety.Text = "'" & LCase(dr2(2)).ToString() & "'"
floating.Text = "'" & LCase(dr2(3)).ToString() & "'"
b = "'" & LCase(dr2(4)).ToString() & "'"
Comptime.Text = "'" & LCase(dr2(5)).ToString() & "'"
End If
any help?????????????????????
Label.Text = String.Format("{0:0}", b)
Will take the number (b) and display it in the label rounded to 0 decimal places, if that's what you mean?
Also, get into the habit of using OO principles, not procedural ones (eg insftead of LCase(Blah) do Blah.ToLower(). Then you'll be learning the .Net Framework, not VB.Net helper methods.
Finally, and most importantly, make sure you turn Option Strict on in project settings. It will force you to use the correct data types but it makes learning easier and gives you ~30% performance boost. Do not code with this setting off.
Edit: Some clarification re: String.Format...
Dim Number = 12345.6789
String.Format("{0}", Number) '12345.6789
String.Format("{0:#,##0}", Number) '12,345
String.Format("{0:0.0}", Number) '12345.7
String.Format("{0:0.00}", Number) '12345.68
String.Format("{0:000,000.00}", Number) '012,345.68
'You can also combine multiple variables...
Dim Number 2 = 10
String.Format("{0}: {1}", Number, Number2) '12345.6789: 10
Ok, editing your code...
If dr2.Read Then
Dim MyNumber = 12345.6789
annual.Text = String.Format("{0:0.00}", MyNumber) '' <-- Setting a string variable (`.Text`) with a number fails. Use the formatted string instead...
FirstName.Text = String.Format("'{0}'", dr2(0).ToLower())
sick.Text = String.Format("'{0}'", dr2(1).ToLower())
Maternety.Text = String.Format("'{0}'", dr2(2).ToLower())
floating.Text = String.Format("'{0}'", dr2(3).ToLower())
'Not sure what you're trying to do here but `b` was a Double and you're trying to set it to a string. If you just want the number do. See below.
b = "'" & LCase(dr2(4)).ToString() & "'"
Comptime.Text = "'" & LCase(dr2(5)).ToString() & "'"
End If
If you have a string containing a number ("123.456") like the one from the database, you can convert it to a double as follows:
Dim InputString = "123.456"
Dim MyNumber = Double.Parse(InputString)
If you want to format a number as a string for display, that's when you use the String.Format I mentioned above.
Incidentally, instead of using Dim without an As (which means create a variable and determine what type it is from how I use it), use specific types until you're familiar with them. Then you'll have a better mental/visual representation of what you're trying to store where...
Also, since you're putting quotes around all your variables, it would make sense to factor that out into a different method...
Public Function QuoteLower(Input as String) As String
Return String.Format("'{0}'", Input.ToLower())
End Function
Then Maternety.Text = String.Format("'{0}'", dr2(2).ToLower()) would become Maternety.Text = QuoteLower(dr2(2))
Be Warned: Quoting strings never works reliably. There are too many edge-cases and someone malicious will be able to exploit your code (What happens when someone's surname is O'Connelly or when they type SQL into your form?). Really you want to be using Parameterised Queries or an ORM (Object Relational Mapping) framework. The most common ones in .Net are the Entity Framework and nHibernate. Something to bear in mind for next time.

Only numbers, disallow letters -user input

I am writing a console application which requires user input of certain values. I want to disallow any letter input. The console automatically writes "Conversion from string "b" to type 'Integer' is not valid." but I want the console to display my personal message "Not a valid number, please try again." how can I do that?
I've tried many different keywords and phrases but none work. Maybe I'm doing it wrong (not unlikely) or maybe it's just meant for something else. Either way I need help.
To recap: User input in a console that only allows numbers not letters, and will display my message.
I didn't want to post my code since people always pick on it, but here it is. Please note that there MUST be an exception. It is homework and I NEED an exception and this is one way a user can screw up. Please don't tell me not to use an exception.
Module Module1
Sub Main()
Try
System.Console.WriteLine("Input up to 10 valid numbers to have them mathematically averaged.")
For Index = 0 To 9
Dim Input As IList
Input = Console.ReadLine()
Next Index
If ' here is where I want to add that numbers only Then
Throw New exception("Not a valid number, please try again.")
Else
System.Console.WriteLine("Now averaging numbers...")
Dim average As Double = (n + n + n + n + n + n + n + n + n + n) / 10
Console.WriteLine("The average of " & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & " and " & n & " is " & average & ".", "Calculation")
End If
Catch e As Exception
System.Console.WriteLine(e.Message)
End Try
End Sub
End Module
Dim inputString = Console.ReadLine
If Integer.TryParse(inputString, num) Then
DoSomething(num)
Else
Console.WriteLine("Not a valid number, please try again.")
End If
Here's one way to do it, honoring your requirements:
Module Module1
Sub Main()
System.Console.WriteLine("Input valid numbers seperated by spaces to have them mathematically averaged.")
Dim inputArray As String() = System.Text.RegularExpressions.Regex.Replace(Console.ReadLine().Trim(), "\s{2,}", " ").Split(New Char() {" "})
Dim values As New ArrayList
Dim sum As Integer
For i As Integer = 0 To inputArray.Length - 1
Try
sum = sum + Integer.Parse(inputArray(i), Globalization.NumberStyles.Integer)
values.Add(inputArray(i))
Catch ex As Exception
Console.WriteLine(String.Format("The value ""{0}"" is not a valid number and will be ignored. ExceptionMessage: {1}", inputArray(i), ex.Message))
End Try
Next
Dim average As Decimal = sum / values.Count
Console.WriteLine(vbCrLf)
Console.WriteLine(String.Format("The average of ""{0}"" is {1}", Join(values.ToArray, ", "), average))
Console.WriteLine(vbCrLf)
Main()
End Sub
End Module
Well for starters, the Try - Catch should be inside the input gathering For loop. As your program is written now, as soon as one wrong value is entered execution jumps to the catch and your program ends! If you try casting your input to an decimal you won't need to throw an exception manually, it will be thrown automatically if your input is not an decimal! Try casting the current console input as a decimal and then add that number to your list.
Dim inputNumber as Decimal = CDec(Console.ReadLine())
Input.Add(inputNumber)
Also n will be the same number every time so how you are doing it won't work (look up the basics of how a list works, how to add elements to a list and how to display list elements)