VB.Net Convert ToDecimal won´t work with comma - vb.net

I´m trying to parse a String to a Decimal but I keep getting a formatException
Dim row as GridViewRow
for each row in grdActieRittenActiefAlt.rows
Dim rbl as RadioButtonList = row.FindControl("tblAddAct")
'toevoegen = true
if rbl.SelectedItem.Value = true then
Dim opgaveIdent as Integer = Convert.ToInt32(grdActieRittenActiefAlt.DataKeys(row.RowIndex).Value.ToString())
Dim curOldTarief as Decimal = Convert.ToDecimal(lblCuratiefTarief.Text)
Dim curOldKorting as Decimal = Convert.ToDecimal(lblCuratiefKorting.Text)
Dim curTariefString as String = row.Cells(4).Text
Dim curKortingString as String = row.Cells(6).Text
Dim curTarief as Decimal = Convert.ToDecimal(curTariefString)
Dim curKorting as Decimal = Convert.ToDecimal(curKortingString)
lblCuratiefTarief.Text = (curOldTarief + curTarief).ToString()
lblCuratiefKorting.Text = (curOldKorting + curKorting).ToString()
end if
next row
The input is 431,25.
So far I've tried the following:
Changing the comma to a colon using .Replace(",",".") => Didn't work
Using a forced CultureInfo => Didn't work
Use the row.Cells(4).Text directly => Didn't work
Use a substring query to get only the round numbers (431) => Worked but is no solution
Does anyone else have any suggestions?

After doing a lot more testing and trying I've found a workaround/solution for the problem.
The row.Cells(4).Text was a boundfield. I've changed that to a TemplateField with a label.
By making a local variable (Label) and using that to convert the decimal from it works. I got no idea why but for me it's a solution for now.

Have you tried the FormatNumber function?
FormatNumber(number, 2)
2 is the number of decimal places.

Related

Using Split in Vb.net in last dash

i have two example
"hcg.com.ph?C402-10A-2012-06132017-22"
"hcg.com.?C3032-1B-2012-06132017-1"
output should be
hcg.com.ph?C402-10A-2012-06132017
hcg.com.?C3032-1B-2012-06132017
but i got
hcg.com.ph?C402 and hcg.com.?C3032
Dim FinalSplt() As String
Dim ItemBaseCode As String
FinalSplt = value.ToString.Split("-")
ItemBaseCode = FinalSplt(0)
How to split in the last dash?
Here is some code that uses Substring and LastIndexOf.
'test input
Dim si() As String = {"hcg.com.ph?C402-10A-2012-06132017-22", "hcg.com.?C3032-1B-2012-06132017-1"}
'use to verify
Dim sv() As String = {"hcg.com.ph?C402-10A-2012-06132017", "hcg.com.?C3032-1B-2012-06132017"}
For x As Integer = 0 To si.Length - 1
Dim s As String = si(x).Substring(0, si(x).LastIndexOf("-"c))
'verify
If s = sv(x) Then
Stop 'verified
End If
Next
Ok, without actually writing code I can see you need to split the string more efficiently.
Firstly, strip the quotes.
Secondly, split the string based on the ? mark.
Take the second string in the array, and split that based on the - mark.
Now you have an array of all the portions, join this array with all except the last element.
Join the new string with the original first part.
Add the quotes back if needed.

How to get value from expression in vb.net

I have the following string expression:
str="1+2+3+4"
Now from this string I want the value of number (10). How can I get this value from this expression?
For that to work, you'd have to parse all the numbers, something like this
Dim str As String= "1+2+3+4"
Dim numbers() As String = str.Split('+')
Dim result As Integer = 0
For Each number As String In numbers
result += Integer.Parse(number)
Next
Here is an alternative solution that uses Linq. This solution excludes nothing it can not parse...
YOURSTRING.Split("+").ToList.Where(Function(sr) Not String.IsNullOrEmpty(sr) AndAlso Integer.TryParse(sr, New Integer)).Sum(Function(s As String) Integer.Parse(s))
Example Output
1+2+3+4 = 10
1+2+3+4++12+1 = 23 (Notice the typo (4++12), it still works even it there's a mistake)

How to convert a string expression to vb code?

I have a string output from user interface as below,
strFormula ="gridControlName.Rows(i).cells("C1").value *
gridControlName.Rows(i).cells("C2").value"
if i write code like
dblRes=gridControlName.Rows(i).cells("C1").value *
gridControlName.Rows(i).cells("C2").value
it will give result.. but since its a string i could not get result
How can I remove the double quotes from the above string and get the values entered in the grid cells to be multiplied?
I don't think there's an 'easy' way to do this, since VB.Net doesn't have an "eval()" like some other languages. However, it does support run-time compilation. Here are a couple articles which may help you:
Using .NET Languages to make your Application Scriptable (VB.Net example)
Runtime Compilation (A .NET eval statement) (C# example)
Both are intended to be a bit more robust than just executing single lines of code, allowing users to input entire textboxes of their own code for example, but should give you some direction. Both include sample projects.
Hi guys thanks for your updates.. I wrote my own function by using your concepts and some other code snippets .I am posting the result
Function generate(ByVal alg As String, ByVal intRow As Integer) As String Dim algSplit As String() = alg.Split(" "c)
For index As Int32 = 0 To algSplit.Length - 1
'algSplit(index) = algSplit(index).Replace("#"c, "Number")
If algSplit(index).Contains("[") Then
Dim i As Integer = algSplit(index).IndexOf("[")
Dim f As String = algSplit(index).Substring(i + 1, algSplit(index).IndexOf("]", i + 1) - i - 1)
Dim grdCell As Infragistics.Win.UltraWinGrid.UltraGridCell = dgExcelEstimate.Rows(intRow).Cells(f)
Dim dblVal As Double = grdCell.Value
algSplit(index) = dblVal
End If
Next
Dim result As String = String.Join("", algSplit)
'Dim dblRes As Double = Convert.ToDouble(result)
Return result
End Function
Thanks again every one.. expecting same in future

how to get value by split in vb.net 2005

i have a database in one field like below 222-225. I try to make split to read that value for my function. Just simple function a=225 b=222 then total=(a-b)+1. here my code
Dgv.CellClick
'Dim x As Boolean
Dim a As Double
Dim total As Double
a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value)
Split(a, "-")
total = (a) - (a)
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
My problem is this doesn't work. I can't get the value that I split. Any idea how to solve this problem?
note: I use VB.NET 2005
If you want total=(a-b)+1 .. That should be
dim b = a.Split("-")
total = val(b(1)) - val(b(2)) + 1
may be this can help. try this...
Dim a As String
a = ""
Dim x As String
Dim total As Double
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString
Dim ary() As String
x = a
ary = x.Split("-")
total = CInt(ary(1)) - CInt(ary(0))
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Like others have said, Split() returns a String array, like this:
Dim SplitValue() As String = Split(a, "-")
total = (CType(SplitValue(1), Double) - CType(SplitValue(0), Double)) + 1
If I read your question correctly, the value you're looking for is 222-225, and that value is located in the specified cell of Dgv (which I'm guessing is a DataGridView). If my understanding is correct, there are a couple of things going on.
First, I'm not sure why you're trying to convert that value to a double with the following line of code:
a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value)
The Item property of a DataGridView holds a DataGridViewCell, and the Value property of the DataGridViewCell returns an Object. Trying to convert 222-225 to a double will, I believe, fail (though since this is VB.NET, it's possible it won't depending on the options you set - I'm not as familiar with VB.NET as I am with C#).
Even if it does successfully work (I'm not sure what the output would be), Split expects a string. I would change that line of code to the following:
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString()
Now you have a string that you can use Split on. The Split you have in your posted code appears to be the Visual Basic (pre-.NET) Split method Split Function (Visual Basic). As others have mentioned, Split returns an array of strings based on the delimiter. In your code, you don't assign the result of Split to anything, so you have no way to get the values.
I would recommend using the .NET version of Split (String.Split Method) - there are several ways you can call String.Split, but for purposes of your code I'd use it like this:
Dim splits As String() = a.Split(New Char() { "-" })
Where a is the string value from the selected DataGridViewCell above. This will give you a 2-element array:
splits(0) = "222"
splits(1) = "225"
The final part is your formula. Since you have strings, you'll need to convert them to a numeric data type:
total = (CDbl(splits(1)) - CDbl(splits(0))) + 1
Which becomes (225 - 222) + 1 = 4.
Putting it altogether it would look something like this:
Dim a As String
Dim total As Double
Dim splits() As String
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString()
splits = a.Split(New Char() { "-" })
total = (CDbl(splits(1)) - CDbl(splits(0))) + 1
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Split returns an array. something like this. VB.Net is not my primary language but this should help.
dim arr = a.Split(New Char (){"-"})
total = ctype(arr(0), double) - ctype(arr(1),double)
Try this:
Dim aux() As String = a.Split("-"c)
total = CDbl(aux(0)) - CDbl(aux(1)) + 1
Dim a As string
Dim x As String
Dim total As Double
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value
Dim ary() As String
x = a
ary() = x.Split("-")
total = CInt(ary(1)) - CInt(ary(0))
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total

Convert a string to decimal in VB.NET

What will be the easiest way to convert a string to decimal?
Input:
a = 40000.00-
Output will be
40,000.00-
I tried to use this code:
Dim a as string
a = "4000.00-"
a = Format$(a, "#,###.##")
console.writeline (a)
Use Decimal.Parse to convert to decimal number, and then use .ToString("format here") to convert back to a string.
Dim aAsDecimal as Decimal = Decimal.Parse(a).ToString("format here")
Last resort approach (not recommended):
string s = (aAsDecimal <0) ? Math.Abs(aAsDecimal).ToString("##,###0.00") + "-" : aAsDecimal .ToString("##,###0.00");
You will have to translate to Visual Basic.
For VB.NET:
CDec(Val(string_value))
For example,
CDec(Val(a))
The result will be 40000D or if the value for a = "400.02" then it will be 400.02D.
Use Decimal.TryParse
Dim a as string
Dim b as Decimal
If Decimal.TryParse(a, b) Then
a = b.ToString("##,###.00")
Else
a = "can not parse"
End If
The following works fine for me, but I don't know whether it is correct or not.
double a = 40000.00;
a = double.Parse(a.ToString("##,###.00"));
MessageBox.Show(a.ToString("##,###.00"));
Sub Main()
Dim convert As Func(Of String, Decimal) = _
Function(x As String) Decimal.Parse(x) ' This is a lambda expression.
Dim a = convert("-16325.62")
Dim spec As String = "N"
Console.WriteLine("{1}", spec, a.ToString(spec))
'Console.ReadLine() ' Uncomment to see value in Console output.
End Sub
Dim D# = CDec(TextBox1.Text) '//convert string to decimal with short
This code works, but it is quite long:
Dim a as string
Dim b as decimal
a = "4000.00-"
b = a
If b >= 0 then
console.writeline (b.ToString("##,###.00"))
Else
b = Math.Abs(b)
console.writeline (b.ToString("##,###.00") & "-")
End if