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
Related
I'm making a program which a user enters an item in a text box and the program will check if the item is in the string. Here is my current code:
Try
Dim Request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("https://www.dropbox.com/s/2l37j6v0ofsenus/Foods.txt?dl=1")
Dim Response As System.Net.HttpWebResponse = Request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(Response.GetResponseStream)
Dim Foods As String = sr.ReadToEnd()
If Foods.Contains(TXTItem1.Text) Then
Dim Substring As String = Foods.Split(TXTItem1.Text)(1)
Dim SubString1 As String = Substring.Split("-")(1)
Dim SPValue As String = SubString1.Split(vbNewLine)(0)
MsgBox("That item is worth " + SPValue + " SmartPoints!", info)
Else
MsgBox("Item is not found in our list!", critical)
End If
Catch ex As Exception
MsgBox("Error")
End Try
I want to make it where when it checks the string, it is not case sensitive. So if a user enters "eggs" and the string contains "Eggs", it will do the function still even tho its lower-case. How can I do this? Thanks!
If you convert the string you're testing to lowercase, and also the string you are testing against to lowercase, then case is no longer a consideration!
There are functions that can do this for you, but the logic behind them is always the same ... Caseless comparison requires both pieces of data to be converted to either all lowercase (or all uppercase), before the comparison is undertaken. I
The linked question that's referred to by #jacob-h in the comment above already has answers to your question, but I prefer an extension method in this case.
Here's an extension method version that I've been using for a while. Add a new Module to your project (or use an existing one if you find it appropriate), and add this extension method to it:
<Runtime.CompilerServices.Extension>
Public Function ContainsIgnoreCase(ByVal s As String, ByVal value As String)
Return s.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0
End Function
Then you can use something like this:
If Foods.ContainsIgnoreCase(TXTItem1.Text) Then
' Do your thing.
End If
I am having an issues with conversion of values that I am trying to reference via a field that I want to format from an ERP System. I am unable to convert all of my values because they are being pulled out as strings, no matter if variables are set to integer or string. What am I doing that would cause this error, should variables be defined a different way?
Public Class Class1
Inherits erp.Rule
Public Overrides Function Execute() As erp.RuleResult
Dim Result As New RuleResult
Try
Dim date_recieved As Date
Dim month As String
Dim period As String
Dim Year1 As String
Dim Year As String
date_recieved = Data.Fields.GetFieldByAlias("date_received").FieldValue
month = Format(date_recieved, "M").ToString
Year = Data.Fields.GetFieldByAlias("yearAR").FieldValue
period = Data.Fields.GetFieldByAlias("periodAR").FieldValue
If period = month Then
If Year = Year1 Then
Exit Function
Else
MessageBox.Show("Date received does not match year", "Invalid Input")
End If
Else
MessageBox.Show("Date received does not match period", "Invalid Input")
End If
Catch ex As Exception
Result.Message = ex.Message
End Try
Result.Success = True
Return Result
End Function
Format does not accept a string parameter, by you passing "M" it is trying to convert the datatype you supply to the datatype the function accepts and since a string does not implicitly cast to an integer an error occurs
To format a Date type to various formats of string you just use your date variable and its subsequent .ToString() method with your formatting rules as an argument of .ToString()
Here is a link to the msdn explaining all the possible formatting options: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
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
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
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