Impicit conversion warning - vb.net

I am doing this simple operation with a string in VB.NET
I have a string of information called segmentInfo looking like this:
XRT0034:3:89:23
So I am just trying to get a number out of it:
Dim rowNum As Integer = segmentInfo.split(":")(1)
And I am getting actually 2 warnings. Both warning are given on the same line of code.
Warning - Implicit conversion from 'String' to 'Integer'
Warning - Implicit conversion from 'String' to 'Char'
Maybe I could understand the first one, about the string to integer...but the second one?? I do not understand.
Anyway, can anybody tell me what I am doing wrong and how to fix it?

The Split method takes a Char (array) as a parameter, not a string. Hence:
.... segmentInfo.split(":"c)(1)
Secondly, you need to parse the resulting string to an integer:
Dim rowNum As Integer = Integer.Parse(segmentInfo.split(":"c)(1))
Do this only when you know that the string is a number. Otherwise, use TryParse.

No such overload method String.Split which take one parameter of type String
From MSDN String.Split Method
You can change to
Dim rowNum As Integer = segmentInfo.split(":"c)(1)
":"c - c is character of type Char Type Characters (Visual Basic)
For converting String to Integer use Int32.TryParse or Int32.Parse method to convert string to integer
Dim rowNum As Int32 = Int32.Parse(segmentInfo.split(":"c)(1))
'Exception will be thrown if string value not convertible to Integer type
Or
Dim rowNum As Int32
If Int32.TryParse(segmentInfo.split(":"c)(1), rowNum) = True Then
'Use succesfully converted integer value
Else
'Show message about invalid text
End If

You must parse it to integer form
Dim rowNum As Integer = Convert.ToInt32(segmentInfo.split(":")(1))

Dim rowNum As Integer = Integer.Parse(segmentInfo.split(":"c)(1))

Related

Check string in an array

I have strings stored in an array and need to check if the 5th character of each string is a number or not. The code I used is:
If Mid(arr(i), 5, 1) = IsNumeric(True) Then
MsgBox("Number")
End If
It is giving an error:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Boolean' is not valid.
You originally tagged your question as vba, but VBA doesn't throw System.InvalidCastException, or any other exception for that matter; vb.net does.
IsNumeric(True) returns True if True is numeric. You want to verify if the string retrieved from the array is numeric; give it the string retrieved from the array as a parameter:
If IsNumeric(Mid(arr(i), 4, 1)) Then
MsgBox("Number")
End If
Your code reads like VB6/VBA though, because of this:
Imports Microsoft.VisualBasic
That namespace contains VB6-like things that you don't need to use at all. The beauty of .net is that everything is an object, so assuming the array is an array of String, you can call the actual String instance methods instead of VB6's Mid function.
Dim theFifthCharacter As String = arr(i).Substring(4, 1)
Or, because you're only interested in 1 character, and a String is itself an IEnumerable(Of Char), you can do this:
Dim theFifthCharacter As Char = arr(i)(4)
Notice the off-by-one - in .net indices start at 0, so if you want the 5th item you'll fetch index 4.
Now, if you want to see if it's numeric, you can try to parse it:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
'numeric: digitValue contains the numeric value
Else
'non-numeric: digitValue contains an Integer's default value (0)
End If
Lastly, if you want a message box, use WinForms' MessageBox instead of VB6's MsgBox:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
'numeric: digitValue contains the numeric value
MessageBox.Show(string.Format("Number: {0}", digitValue))
Else
'non-numeric: digitValue contains an Integer's default value (0)
MessageBox.Show("Not a number")
End If
A more correct way to do this would be:
If Char.IsDigit(arr(i)(4)) Then
Your syntax is incorrect. It should be:
If IsNumeric(Mid(arr(i), 5, 1)) Then

TryCast for string to integer in VB.NET

I do not understand at all how to use TryCast in my code, but it is something I need to use for validating user input. I have done various searches and looked at various questions on here, but no one seems to actually say how to use it, and the MSDN website doesn't seem to help at all.
Function ValidateInput(Var_In As String) As Integer
If TryCast(Var_In, Integer) = Nothing Then
Return vbNull
Else
Return Var_In
End If
End Function
The error says that
The operand must be of reference type but Integer is of value type
What is the explanation of what I have done wrong?
TryParse doesn't accept more than 10 digits so for example, an input of "12345678901" won't be accepted. How do I fix this?
Let's try to understand the differences between TryCast, Convert and TryParse.
TryCast
This function will attempt to convert one object into another type, as long as it is a reference type.
Dim MyNewObject = TryCast(MyObject, MyReferenceClass)
If IsNothing(MyNewObject) Then
MessageBox.Show("Impossible to cast")
End If
Since Integer is a value type, it will not work, so we have to figure something out...
Convert
Convert Class on MSDN
From MSDN:
Converts a base data type to another base data type.
So we can try:
Dim myInt = Convert.ToInt32(MyObject)
The problem is that it will generate an exception InvalidCastException if it's impossible to do the conversion.
TryParse
This function is trying to convert a String into something you want. And it will not generate an exception:
Dim myInt As Integer = 0
If Not Integer.TryParse(MyString, myInt) Then
MessageBox.show("This is not an integer")
End If
Limitation
Converting a String into a Integer can sometimes be tricky... If the String represents a number that is greater or lesser than Integer.MaxValue and Integer.MinValue, you will end up with no conversion...
So you can go with a Double:
Double.TryParse(MyString, MyDouble)
Or personally, if you know that it will be a number, use Decimal:
Decimal.TryParse(MyString, MyDecimal)
See Decimals on MSDN
Decimal still has a Max and Min value, according to MSDN:
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors.
Convert.ChangeType
This one is also interesting, but is a bit weird...
You are attempting to perform TryCast against an Integer, which is a value type. TryCast works only on reference types, such as (but not limited to) a Class, Object, or String type.
If you are trying to convert the input parameter to an Integer, you might try one of the methods in the Convert class, such as Convert.ToInt32() or Integer.TryParse.
Instead of TryCast, use TryParse:
Function ValidateInput(Var_In As String) As Integer
Dim iNum As Integer
If (Integer.TryParse(Var_In, iNum)) Then
Return iNum
Else
Return vbNull
End If
End Function
Much better is to use TryParse:
Function ValidateInput(Var_In As String) As Integer
Dim num as Integer
If Not Integer.TryParse(Var_In, num) Then
Return vbNull
Else
Return num
End If
End Function
I'm late to the discussion, but if anyone lands here (like I did) looking for a quick & dirty solution, here a function I'm using for simple cell validation in a DataGridView control.
Function TryTypeFit(theString As String, theType As Type, ShowError As Boolean) As Boolean
Dim TempReturn As Boolean = False
Dim TempObject As Object
Try
TempObject = Convert.ChangeType(theString, theType)
TempReturn = True
Catch ex As Exception
' didn't work
TempReturn = False
If ShowError Then
Dim eMessage As String = "Error: Value must be castable to a " & CStr(theType.Name)
MsgBox(eMessage)
End If
End Try
100:
Return TempReturn
End Function

Convert string to integer with CINT

Const gconintRows1st As Integer = 15
Const gconintRows4th As Integer = 20
I am trying to convert String to Integer
by using:
intNumber = CInt(strNumberSelected(intFirst5Balls))
Professor's
intTemperature = CInt(strTemperatures(intMonth))
But some how this does not work.
The professor's version worked fine but I cannot figure out why the intNumber does not.
Yes, this is my first time doing vb
It looks like strNumberSelected is a string array, correct? And you're asking for the string in the array at position intFirst5Balls?
Take this for an example:
Dim strArray As String() = Split("Hi|there|everybody", "|")
The Split() function will split our long string at each occurrence of a pipe ("|").
The resulting string array will have the following 3 elements:
"Hi"
"there"
"everybody"
And you'd reference these elements by their indexes:
strArray(0) = "Hi"
strArray(1) = "there"
strArray(2) = "everybody"
If you're getting the error 'Char' values cannot be converted to 'Integer' then your array is more likely an array of type Char, and the CInt() function cannot convert it to an integer.
You can use
Integer.TryParse()
to try to get a valid Integer from your array, but it sounds a bit like you're unsure what sort of data actually lives in the array.

VBA How to declare an array with elements with different datatype

I have an array that I have created to store error records and it has the following elements:
Serial No,File name, error type, error cell, error cell value
As of now I have declared my array like this and then I populate the values later on.
Dim errorArray() As String
But ideally, I want Serial Number to be a proper integer, but it is getting converted into string. I don't know how to declare this correctly so that I can have Long datatype for the first element and string for the next 3 and variant for the last one.
Create a private type in your code, like this:
Private Type ErrRecord
SerialNo As Long
FileName As String
ErrorType As String
ErrorCell As String
ErrorCellValue As Variant
End Type
And then in your routine, call it like this:
Dim errorArray(0) As ErrRecord
With errorArray(0)
.SerialNo = 12345
.FileName = "Test.xls"
.ErrorType = "Bad error"
.ErrorCell = "1234"
.ErrorCellValue = "Test"
End With
You'll want to create an array of type Variant. An array of type Variant can store any data type in any of its elements.
Dim astrItems(0 To 9) As String
Dim varItems As Variant
varItems = astrItems

splitting a string in VB

I have a ComboBox which I assign to a variable:
Dim var as String = ComboBox1.SelectedValue
Dim name As String = var.Split(",")
This gives me the error
Value of type '1-dimensional array of string' cannot be converted to String
Any ideas as to where I'm going wrong?
Split returns an array of strings. Your variable needs to be changed to an array, not just a single string.
My VB is a bit rusty, but I think you have to make name an array:
Dim name() As String = var.Split(",")
name needs to be declared as an array.
dim name() as string = var.split(",")
The split() method will break up the string based on the given character and put each newly created string into an array and return it.
This is what your error message is telling you:
Value of type '1-dimensional array of string' cannot be converted to String
The method returns an array of string, but your trying to put it into just a string!
EDIT: In response to your answer...
So far you've managed to split the string yourself with the split method. To output this to your message box, you need to concatenate the two elements in the proper order:
msgbox(name(1) & " " & name(0))
Notice I indexed the array twice! Element 1 is the first name, element 0 is the last name. Remember you got this name in lname,fname format. Passing the array itself doesn't make sense! Remember, a datatype is not equal to an array of that type, they are two different things. Therefore a string is not compatible with a string array. However, each individual element of the array is a string, and so each of those are compatible with the string type (because they're the same thing)!
Dim var As String = ComboBox1.SelectedValue
Dim temp() As String = Split(var, ",", -1, CompareMethod.Binary)
Dim name As String = temp(0)
Or maybe "name" isn't an array and the goal is to populate "name" with everything up until the first comma, in which case the fix would be:
Dim name as String = var.Split(",")(0)
Note: assumes that var is not Nothing.