VB why DBnull? Operator '*' is not defined for string "11106.9" and type 'DBNull' - vb.net

i just want calculate amount with percent on database access.
this my code
xlWorksheet.Range("AI" & CurrentRow2).Value = Format(CDbl(strGetAccrualAllocation*ADORS_Temp1.Fields("PERCENTAGE").Value).ToString("N2"))
and this error respond
System.InvalidCastException: Operator '*' is not defined for string
"11106.9" and type 'DBNull'.
thankyou

It is always wise to check data used in a calculation for NULL. I often use the inline if to do that, for example:
IIF(IsDBNull(MyValue),0,MyValue)
If MyValue is null, zero is returned, if not, the value of MyValue is returned.
Or if you need to indicate to the user that a value is null:
If IsDBNull(MyValue) Then
'message to user that vaslue is null or some other action
Else
'perforn calculation
End If
When using a string of numeric characters, implicit conversion from string to value will take place. If there is any chance that the string could contain anything other than numeric characters, you should test for that, otherwise another error will be generated.

Related

IsNumeric() allowing minus at last of the values

I am using IsNumeric() function in my code to validate numbers.
IsNumeric(100) - true,
IsNumeric(-100) - true,
IsNumeric(+100) - true,
IsNumeric(100-) - true - I have doubt in this. (100-) Is this a valid number? IsNumeric () returns true to this value.
Dim latitude As String = "12.56346-"
If IsNumeric(latitude) Then
If (Convert.ToDouble(latitude) >= -90 And Convert.ToDouble(latitude) <= 90) Then
isValidLatitude.Text = "true"
Else
isValidLatitude.Text = "false"
End If
Else
isValidLatitude.Text = "false"
End If
Error while converting latitude to double
Input string was not in a correct format.
IsNumeric is from the Microsoft.VisualBasic namespace/dll, a bunch of helper stuff intended to help VB6 programmers get their arcane VB6 code /knowledge working on VB.NET
You'll note if you use other functions from the same dll such as Microsoft.VisualBasic.Conversion.Int(), or you use dedicated VB.NET converters such as CInt or CDbl these will also cope with a trailing minus sign and return a negative value
If you want to dispense with the old ways of VB6, use a numeric type's TryParse.. but all in, be consistent / if you use a function from Microsoft.VisualBasic to determine if a conversion can be made, use the vb conversion because within itself the package will be consistent but between Microsoft.VB and normal .net System there are some differences in behavior
Edit:
A couple of people have been wondering about the source code and how it uses TryParse, so why doesn't it work like using TryParse directly?
Microsoft.VisualBasic.Information.IsNumeric() uses Microsoft.VisualBasic.CompilerServices.DoubleType.TryParse() to determine whether an expression is numeric. This DoubleType.TryParse is not the same as Double.TryParse - it is a helper method again in the VB namespace that specifically sets the NumberStyles.AllowTrailingSign flag among many other flags. When parsing the number (first as non currency related, using Double.Parse, then if it fails a second attempt is made using adjusted values for currency related tests) this AllowTrailingSign flag will be considered in conjunction with other regional number formatting rules in determining if the passed in value is numeric
You'll note that on a machine obeying a USA number formatting culture, a string of "(100$)" is also declared to be numeric but calling Double.TryParse("(100$)", x) will also return false. The VB helper methods here are being a lot more liberal in what they accept than the System methods, because they're telling the System methods to be more liberal than they are by default
As noted, I've always regarded the Microsoft.VisualBasic namespace as a bunch of helper methods intended to allow terrible old VB6 code to be pasted into VB.NET and work with minimal fiddling. I wouldn't advocate using it for new projects and I remove the reference when I work on VB.NET - using it to support the VB6 notions of "just sling anything in, of any type, and it'll probably figure it out and work.. and if it doesn't we can always on error resume next" should be discarded in favour of precise and accurate about the operations executed and their intent
Note: my previous answers were wrong about assuming it was a bug. As the answer of #Damien_The_Unbeliever states, this function tries to validate the string as a lot of data types. And actually, the value "100-" is a valid Decimal number. That's why it returns true (as it's a "valid" Decimal) but gives a exception when converting to Double (as it's not a valid Double). #Damien_The_Unbeliever really deserves your +1 for pointing that.
From the documentation (showing all the data types that IsNumeric tries to validate):
IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short, Single, UInteger, ULong, or UShort. It also returns True if Expression is a Char, String, or Object that can be successfully converted to a number. Expression can contain non-numeric characters. IsNumeric returns True if Expression is a string that contains a valid hexadecimal or octal number. IsNumeric also returns True if Expression contains a valid numeric expression that begins with a + or - character or contains commas.
Also, #CaiusJard did a nice search and pointed out that inner methods use a NumberStyles.AllowTrailingSign option, which allows this behavior.
Ok, now to the solution:
Just use a TryParse method, from your desired data type (int, long, etc...). The cool thing is that it'll behaves exactly as you expect, and if the parsing is successful, we have the parsed value already available to use!
if (Int32.TryParse(value, out int number))
{
// String is a valid number, and is already parsed in the 'number' variable!
}
else
{
// String is not a valid number!
}
Solution's VB.Net version:
Dim value As String = "12.56346-"
Dim number As Double = 0
If Double.TryParse(value, number) Then
' String is a valid number, and is already parsed in the "number" variable!
isValidLatitude.Text = "true"
Else
' String is not a valid number!
isValidLatitude.Text = "false"
End If
IsNumeric answers a question no sane person wants to ask. As quoted by Vitox's answer:
IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short, Single, UInteger, ULong, or UShort. It also returns True if Expression is a Char, String, or Object that can be successfully converted to a number.
Note, it doesn't tell you that the given string can be converted to all numeric types. It tells you that the string can be converted to at least one numeric type. And for bonus bad style points, of course, it doesn't tell you which types the string can be converted to.
Decimal.Parse("100-") will execute perfectly well and give you a Decimal containing a value of -100.
So, it's not a bug, it's a bad function that has been retained for backwards compatibility reasons. Nowadays, we know better, and that we want to test whether a string can be converted to a specific data type, for which the TryParse family of functions have been designed.

SSRS Report builder LENGTH expression & size specific field

I'm trying to build a bank file using SSRS report builder (3.0). I'm running into two issues:
I'm trying to get a length expression to work on a check number field but LEN(Field) doesn't work (returns 4 as the value regardless of the actual length of the field).
And LENGTH(Field) gives me an error:
The Value expression for the textrun 'Textbox15.Paragraphs[0]. TextRuns[0\' contains an error: [BC30451] Name 'LENGTH' is not declared*
The only reason why I'm even trying to get #1 to work is because I need to have one of the fields on the bank file have a constant length. Regardless of the check number, I need to make sure this field is always at 14 characters with leading zeros. I thought the best way to do this is to do a switch statement and add the number of appropriate zeros in depending on the size of the check number field.
Thanks for the help.
Edit: using a SQL server DB
For the length issue:
There are two ways to get string length
Using the LEN function
= LEN(Fields!myfield.Value)
Using the length property
= Fields!myfield.Value.Length
If your field is not a string, try converting first by using the Cstr function
= LEN( Cstr(Fields!myfield.Value) )
= Cstr(Fields!myfield.Value).Length
For the formatting issue:
For numeric fields set the cell format expression to have as many zeros as required eg. for 14 digit numbers
= "00000000000000"
I don't know on which database you are working if you are using sql server then try LEN
function and LENGHT in oracle.
I think you first convert it into integer if it's character and then try len function.

VBA IsNumeric going WILD

Please explain why the below code behaves randomly
The below line of code returns TRUE when it should have return FALSE
?Isnumeric("555-")
Also
?Isnumeric("555-"/2) returns TRUE
Please explain this random behavior of IsNumeric?
Although it is a bit esoteric the trailing minus is a valid numeric format sometimes used in accounting packages. I guess it is not used so much nowadays. It indicates a negative number e.g. 555- is -555. Your second example works because -555 (or 555-) can be divided by 2 i.e. -227.5 (or 227.5-).
You can see in the Excel UI where it allows the format as part of Text to Columns:
Also, you can set-up a number format to use trailing negative:
#,##0;#,##0-
See this blog-post.
From Microsoft:
IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short, Single, UInteger, ULong, or UShort, or an Object that contains one of those numeric types. It also returns True if Expression is a Char or String that can be successfully converted to a number.
IsNumeric returns False if Expression is of data type Date or of data type Object and it does not contain a numeric type. IsNumeric returns False if Expression is a Char or String that cannot be converted to a number.
Looks like it interprets "555-" as -555.
After checking IsNumeric, you may detect this situation like this:
Cstr(CLng("555-")) = "555-"

Log() behaviour and number# notation

Below example from Excel Help about VBA Log function, notation number# makes conversion of numberinto decimal data type, but makes it any difference for Log function if it takes 10 instead of 10# as an argument ?
Static Function Log10(X)
Log10 = Log(X) / Log(10#)
End Function
To explain why it won't make a difference I need to explain how type conversion is handled in VBA.
In VBA, by default types are attempted to be implicitly converted to the type required by a function/operation, using the default conversions based on your system locale (the system locale bit has meaning when it comes to dates and converting numbers as strings to a numeric type and vice versa).
Consider:
Dim aNumber As Integer, aString As String
aString = 1 & 2
aNumber = aString
aNumber = aString + 1
MsgBox aNumber
In the above, the numbers 1 and 2 are implicitly converted to strings. As system locale doesn't matter when dealing with integral types, aString subsequently is storing "12". Assigning a string to a number results in the string being implicitly converted to a number, so aNumber subsequently is 12, then 13 after the addition. Calling MsgBox passing in a number will result in the number being converted to a string before it is passed in.
Implicit type conversion like the above cannot be disabled in VBA, unlike in VB that has the Option Strict directive.
So, for your Log question above, an integral type passed in will be implicitly converted to a double before actually being passed in. Passing in e.g. 10# compared to 10 will save the conversion (an utterly irrelevant performance consideration) but otherwise is semantically equivalent.

VBA: Does Str(myString) do the same as Str(CDbl(myString))?

Question: Can I assume that Str(myString) will always return the same result as Str(CDbl(myString)) (assuming that myString is statically typed as a string)?
Context:
I am trying to understand VBA's implicit conversions. So far, it appears to me that Str(myString)
implicitly parses myString into a double (culture-sensitive) and then
converts the result into a culture-insensitive string.
For example, using a German locale (i.e. using , as the decimal separator), it holds that
" 1.2" = Str(1.2) = Str("1,2") = Str(CDbl("1,2"))
Since these implicit conversions contain a lot of "magic" to me, I am trying to rewrite a procedure that uses an implicit conversion (Str(myString)) to one using explicit conversion without changing the behavior.
Unfortunately, the documentation is wrong and, thus, useless. (The documentation claims that the argument to Str is interpreted as a Long, which is obviously rubbish: If that were the case Str(1.2) could never yield " 1.2".)
Your statement is true. Str(x) and Str(Cdbl(x)) give identical result provided that x is String data type and contains a valid number.
I made a small test to get convinced.
I used Excel, but it holds the same with Access.
Public Function myStr(txt As String) As String
myStr = Str(txt)
End Function
Public Function myStrCDbl(txt As String) As String
myStrCDbl = Str(CDbl(txt))
End Function
I tried with some key values (0, 1.2, 1E+307, 1E-307, ...) : result of myStr and myStrCDbl are always identical.
I also agree with you that the documentation is wrong. If Str() argument would be interpreted as Long, then Str(1.2) would give "1", because Long is an integer type.
In the mean time, I've found the VBA language specification and can confirm that the spec also answers the question with "yes":
CDbl, when receiving a string, performs a Let-coercion to Double:
If the value of Expression is not an Error data value return the Double data value that is the result of Expression being Let-coerced to Double.
Str, when receiving a string, first performs a Let-coercion to Double and then applies Str:
[If Number is a String,] the returned value is the result of the Str function applied to the result of Let-coercing Number to Double.