"Format Exception was Unhandeled" in vb.net - vb.net

What is wrong here in the code
Dim sReaderList As String
sReaderList = New System.String(vbNullChar, 1024)
Dim x As Integer = Convert.ToInt32(sReaderList)
When debug it produce "Format Exception was Unhandeled"
and Input string was not in a correct format in vb.net

Convert.ToInt32 throws a format exception when the given string either contains invalid characters or is an empty string (note that Nothing would be ok, but '' is not).
As mentioned by Marco you have to catch the exception or be sure that the string contains only valid numerical characters (and vbNullChar is not one of those). Also: if the possibility of empty strings arises, you have to manually check for this or again catch the exception.

The error is happening because you are trying to convert something to an integer which cant be converted so it is throwing an exception.
There are two approaches you can use to solve this problem:
1) Wrap it all in a try / catch block
Dim sReaderList As String
sReaderList = New System.String(vbNullChar, 1024)
Try
Dim x As Integer = Convert.ToInt32(sReaderList)
Catch ex As Exception
End Try
2) use the Tryparse method
Dim i As Integer
Dim s As String = String.Empty
Dim result As Boolean
result = Integer.TryParse(s, i)
If (result) Then
'Code here
End If

You're trying to convert a string filled with non digits to integer... so you're getting the error.
Did you expect something different? Why?
If you want to catch the exception, you could do
Dim sReaderList As String
sReaderList = New System.String(vbNullChar, 1024)
Try
Dim x As Integer = Convert.ToInt32(sReaderList)
Catch
' Manage the error here
End Try
Note, just for example, that if you insert a digit at the beginning of the string, the error disappear.
sReaderList = "1" & sReaderList
Dim x As Integer = Convert.ToInt32(sReaderList) ' This works

Related

How to multiply label and textbox and than show result in another label in vb net?

So this is what i have for now and it triggered me an error "input string not in correct format". I am new to vb net.
Dim total1a = Integer.Parse(lblPrice1a.Text) * Integer.Parse(txtQuantity1a.Text)
Dim value As String = Convert.ToString(total1a)
lblTotal1a.Text = value
Try Below code. As a best practice use TryParse Methods for data type conversion. Since label is not editable, its wiser that else code throws exception.
Dim price As Integer
Dim quantity As Integer
If Integer.TryParse(lblPrice1a.Text, price) Then
If Integer.TryParse(txtQuantity1a.Text, quantity) Then
lblTotal1a.Text = (price * quantity).ToString
Else
MessageBox.Show("Please enter valid quanity.")
End If
Else
Throw New Exception("lblPrice1a price is not an integer.")
End If
The error you're getting
input string not in correct format
Means that one of the two strings that you are parsing isn't able to be parsed.
Dim total1a As Integer
Dim price As Integer
Dim quantity As Integer
Try
price = Cint(lblPrice1a)
Catch ex As Exception
'Code for whatever happens if it goes wrong
End Try
Try
quantity = Cint(lblQuantity1a)
Catch ex As Exception
'Code for whatever happens if it goes wrong
End Try
total1a = price*quantity
lblOutput.Text = Cstr(total1a)
Those try catch statements prevent an exception from being thrown if, say, the user enters "popcorn" for quantity. CInt also works just as well as Integer.Parse(), in my experience.

I wrote a code which reverses a string (and it does), but I don't think it's the clean/right way to do it

I wanted to get familiar with the built-in functions of VB, specifically, the len() function.
However, I think this may not be the right way to concatenate a string with a char.
Also, it may interest you that the error list says,
"Warning 1 Variable 'reverse' is used before it has been assigned a
value. A null reference exception could result at runtime."
I executed the program but it ran fine. Here's the code:
Sub Main()
Dim a As String
Console.WriteLine("Enter the value of the string you want to reverse: ")
a = Console.ReadLine()
Dim reverse As String
Dim temp As Char
Dim str As Integer
str = Len(a)
For x = str To 1 Step -1
temp = Mid(a, x)
reverse = reverse + temp
Next x
Console.WriteLine(reverse)
Console.ReadKey()
End Sub
I'm still learning this language and so far it's been really fun to make small programs and stuff.
Dim TestString As String = "ABCDEFG"
Dim revString As String = StrReverse(TestString)
ref: https://msdn.microsoft.com/en-us/library/e462ax87(v=vs.90).aspx
You are getting the warning
"Warning 1 Variable 'reverse' is used before it has been assigned a
value. A null reference exception could result at runtime."
Because String variable reverse is not yet initialized. Compiler will consider the scenario that For is not executing in such situation the reverse can be null. you can get out of the warning by assigning an empty value to the string: ie.,
Dim reverse As String=String.Empty
You can do the functionality in the following ways too:
Dim inputStr As String = String.Empty
Console.WriteLine("Enter the value of the string you want to reverse: ")
inputStr = Console.ReadLine()
Dim reverse As String = String.Join("", inputStr.AsEnumerable().Reverse)
Console.WriteLine(reverse)
Console.ReadKey()
OR
Dim reverse As String = String.Join("", inputStr.ToCharArray().Reverse)

How to find indexes for certain character in a string VB.NET

I'm beginner with VB.net.
How do I read indexes for certain character in a string? I read an barcode and I get string like this one:
3XXX123456-C-AA123456TY-667
From that code I should read indexes for character "-" so I can cut the string in parts later in the code.
For example code above:
3456-C
6TY-667
The length of the string can change (+/- 3 characters). Also the places and count of the hyphens may vary.
So, I'm looking for code which gives me count and position of the hyphens.
Thanks in advance!
Use the String.Splt method.
'a test string
Dim BCstring As String = "3XXX123456-C-AA123456TY-667"
'split the string, removing the hyphens
Dim BCflds() As String = BCstring.Split({"-"c}, StringSplitOptions.None)
'number of hyphens in the string
Dim hyphCT As Integer = BCflds.Length - 1
'look in the debuggers immediate window
Debug.WriteLine(BCstring)
'show each field
For Each s As String In BCflds
Debug.WriteLine(String.Format("{0,5} {1}", s.Length, s))
Next
'or
Debug.WriteLine(BCstring)
For idx As Integer = 0 To hyphCT
Debug.WriteLine(String.Format("{0,5} {1}", BCflds(idx).Length, BCflds(idx)))
Next
If all you need are the parts between hyphens then as suggested by dbasnett use the split method for strings. If by chance you need to know the index positions of the hyphens you can use the first example using Lambda to get the positions which in turn the count give you how many hyphens were located in the string.
When first starting out with .NET it's a good idea to explore the various classes for strings and numerics as there are so many things that some might not expect to find that makes coding easier.
Dim barCode As String = "3XXX123456-C-AA123456TY-667"
Dim items = barCode _
.Select(Function(c, i) New With {.Character = c, .Index = i}) _
.Where(Function(item) item.Character = "-"c) _
.ToList
Dim hyphenCount As Integer = items.Count
Console.WriteLine("hyphen count is {0}", hyphenCount)
Console.WriteLine("Indices")
For Each item In items
Console.WriteLine(" {0}", item.Index)
Next
Console.WriteLine()
Console.WriteLine("Using split")
Dim barCodeParts As String() = barCode.Split("-"c)
For Each code As String In barCodeParts
Console.WriteLine(code)
Next
Here is an example that'll split your string and allow you to parse through the values.
Private Sub TestSplits2Button_Click(sender As Object, e As EventArgs) Handles TestSplits2Button.Click
Try
Dim testString As String = "3XXX123456-C-AA123456TY-667"
Dim vals() As String = testString.Split(Convert.ToChar("-"))
Dim numberOfValues As Integer = vals.GetUpperBound(0)
For Each testVal As String In vals
Debug.Print(testVal)
Next
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
End Try
End Sub

Too many arguments to '' in VB.net

I'm trying to save from list field that have more than one data on it, how to save all of it at once?
I've try this code
Dim detail As New Detail
Dim detailBr As New DetailBridge
Dim i As Integer
For i = 0 To lstProduct.Items.Count - 1
detail = detailBr.Insert(Convert.ToInt32(ddlGroup.SelectedValue), lstProduct.Items(i).Value) 'error was here
Next
but I got an error in lstProduct.Items(i).Value the error said
Too many arguments to '...'
I'm not sure what the error is.
can anyone help? Thanks for advice.
UPDATE : detailBr is class and the code is
Public Function Insert(ByVal GroupID As Integer, ByVal ProductID As String) As Boolean
Dim iResult As Integer
Dim arrColumn() As String = {"GroupID", "ProductID"}
Dim arrValue() As Object = {GroupID, ProductID}
oConn.Open()
Dim SQLString As String = GenInsert("DetailGroup", arrColumn, arrValue)
Try
iResult = SCommand.Execute(SQLString, oConn)
Catch ex As Exception
Throw ex
Finally
oConn.Close()
End Try
If iResult > 0 Then
Return True
Else
Return False
End If
End Function
The problem here is with the GenInsert Function. Its last two arguments are arrays.
Dim arrColumn() As String = {"GroupID", "ProductID"}
Dim arrValue() As Object = {GroupID, ProductID}
Dim SQLString As String = GenInsert("DetailGroup", arrColumn, arrValue)
A procedure can define only one parameter array, and it must be the last parameter in the procedure definition. MSDN
In simple words you can have only one parameter as array in GenInsert function either arrColumn or arrValue
However, to solve your current problem you can use two dimensional array as parameter as in passing-two-dimensional-array-through-functions and MSDN: Arrays as Return Values and Parameters

Display currency in System.Data.DataTable

I'm working on some old VB code which creates a System.Data.DataTable and defines some columns. It works fine, except that I need a certain column to display as currency, not just a floating point number. How do I this?
Dim myDataTable As New System.Data.DataTable("tblRec")
myDataTable.Columns.Add("RECAMOUNT", System.Type.GetType("System.Double"))
Protected WithEvents DataGridCurrentCRLines As Global.System.Web.UI.WebControls.DataGrid
Session("CRLines") = myDataTable
DataGridCurrentCRLines.DataSource = Session("CRLines")
Changing the line to:
myDataTable.Columns.Add("RECAMOUNT", System.Type.GetType("System.Decimal"))
makes no difference, by which I mean the 1234567.89 is displayed, not 1,234,567.89
#Time Schmelter's hint points in the correct direction.
First change the type to string:
myDataTable.Columns.Add("RECAMOUNT", System.Type.GetType("System.String")
then I wrote a helper method to convert a String to a currency String, It appears that one cannot convert from String directly to a currency String, but rather you have to to String -> Decimal -> Currency String
Private Function ConvertStringToCurrencyString(ByVal inputString As String) As String
Dim currencyString As String
currencyString = ""
Dim myDecimal As Decimal
Try
myDecimal = System.Convert.ToDecimal(inputString)
currencyString = myDecimal.ToString("C2")
Catch exception As System.OverflowException
System.Console.WriteLine("ConvertStringToCurrencyString(): Overflow in string-to-decimal conversion.")
Catch exception As System.FormatException
System.Console.WriteLine("ConvertStringToCurrencyString(): The string is not formatted as a decimal.")
Catch exception As System.ArgumentException
System.Console.WriteLine("ConvertStringToCurrencyString(): The string is null.")
End Try
Return currencyString
End Function