convert string to double in vb.net - vb.net

data table contain column named as Fld_primary. this column contain value like 0.00 it is double datatype in mysql table.i want store that datatable value in double variable. am always getting error when i convert to double datatype.
my code
-------
Dim ds5 As dataset1.DTSUMDataTable = TA5.GetData(users)
Dim dttot As Double
dttot = CType(ds5("fld_primary").ToString, Double)
Error
Conversion from string "fld_primary" to type 'Integer' is not valid.

Edited # 3:01 AM with most recent screen caps.
Sometimes I find myself second guessing certain code based on people's answers, but I went ahead and took the time to check if the code that they are all using is even valid:
As you can see that code is a no go, so I used the correct code you see at the bottom there to reference a column.
However, if you wish to get a single cell use the chunk of code below that uses the foreach loop (the rest is my basic setup to show you how it works):
"Y" will equal the value of the datatable cell and you may convert it using the Double.Parse() method:
Dim y = Double.Parse(zDataRow("cat").ToString())
Be careful, if you have multiple rows you will notice that the value of y will change as it makes its way through all the rows.

you can convert it using the Convert class.
Dim dttot As Double = Convert.ToDouble(ds5("fld_primary"))

Your error is actually: ds5 expects an integer as a parameter, so using ds5("fld_primary") is not valid in your code. Perhaps you can try ds5(0)("fld_primary").
After you fixed it, use
dttot = Double.Parse(whatever_string_you_should_put_here)
If you cannot ensure your string must be a valid double, then use Double.TryParse.

You are better off using the 'Double.TryParse' way of converting as this handles any errors better and simply returns a boolean if succesful or not, using 'parse' will throw an exception which isnt anywhere near as elegant.
Dim dub as Double = 0
Double.TryParse("Your String Here", dub)

Try using Double.TryParse(text,value)

Try using this:
For a=0 to yourgridview.rows.count-1
Yourgridview.rows(a).cells(targetcolumnnumber).value=cdbl(Yourgridview.rows(a).cells(targetcolumnnumber).value)
Next

Related

InvalidCastException Conversion from string "" to type 'Double' is not valid

I'm developing a system that shows the total amount paid of a student from the database. For some students that only have a few transactions the function below gives an error Conversion from string "" to type double... but if a student doesn't have any data entry or the values are zero-to-many the code below encounters it. What should I do? Do I need to adjust the code? Please help.
I have here an Function that gets the total items.
Function Totalpaid() As Double
Dim i As Integer
For i = 0 To ((tbl_receipt.Items.Count) - 1)
Totalpaid = (Totalpaid + tbl_receipt.Items(i).SubItems(3).Text)
Next
End Function
You're trying to add two numbers but one of the operands is not a number. You're assuming that the Text of the subitem will be converted a number and added to the running total. At least one of your subitems is blank though. Maybe you consider that to represent zero but it doesn't. It doesn't represent any number at all so the operation fails.
What you should be doing is validating and converting the subitem contents yourself and then providing the system with two Double values to add. If there is no value then you either ignore that subitem or use zero explicitly. Option Strict On will at least force you to perform the conversion but it's still up to you to provide the validation if there's any chance that the data will not be valid.
To me this looks like a problem with your data rather than the code directly. I would recommend sanitising your data before trying to use it in a calculation, i.e.:
Function Totalpaid() As Double
Dim i As Integer
Dim val as Double
For i = 0 To ((tbl_receipt.Items.Count) - 1)
If Double.TryParse(tbl_receipt.Items(i).SubItems(3).Text, val) Then
Totalpaid = (Totalpaid + val)
End If
Next
Return Totalpaid
End Function
The message Conversion from string "" to type double... is saying that your are trying to convert an empty string to a Double which cannot work.
As a side note, when testing your code I did have to include the line Return Totalpaid, I don't know if this was missed when you where writing out the question.

Problems converting string to DateTime

I am making a program in which there is a function that check the database for user that haven't been called for 2 weeks or more, and shows them in a ListView.
In this part I am checking how long ago they were called:
Dim r As Int32 = excelWS.UsedRange.Rows.Count
Dim bel As New ArrayList
For nm As Int32 = 1 To r Step 1
If Convert.ToInt32(DateDiff("ww", Date.ParseExact(excelWS.Cells(nm, 1).value(), "yyMMddhhmm", System.Globalization.DateTimeFormatInfo.InvariantInfo), Now, FirstDayOfWeek.Monday, FirstWeekOfYear.Jan1)) >= My.Settings.Tijdverschil Then
bel.Add(nm)
End If
Next
I get the FormatException was unhandled at the if line.
In the error description it says (roughly translated to english):
The tokens aren't recognized at valid DateTime.
--edit--
If anyone thinks the format in excel is wrong, i copied one field over, they are all like this.
1408180736
Without additional information, I wonder if your date from Excel is coming in as an OLE Automation Date. Depending on how you read the data from Excel, it may come back in this format.
If it is, you need to parse it as a double and then as an OLEDate. Something like this:
Dim oleDate as Double
Dim result as DateTime
If Double.TryParse(excelWS.Cells(nm, 1).value(), oleDate) Then
' Handle valid OLE Automation dates...
result = DateTime.FromOADate(oleDate)
End If
The trick for this is include a datetime picker in your application set visibility to false.
Then set the string as value to the datetime picker and make use of the datetime picker to get the difference between dates.

dr.Item("Value1") has value but always return 0 when assigned to another variable

I need to modify some VB.net code. There is a strange problem that I am facing. I am retrieving value from a DataTable and trying to assign it to a variable. When I check the value of some column in QuickWatch window then it has value but when I assign it to a variable then 0 is returned to the variable. Below is the simple statement that is causing the problem.
Dim MyAmount As Double = Double.Parse(dr.Item("Amount").ToString)
In the QuickWatch window when I check dr.Item("Amount") then it has value 30.12 and after executing the above statement MyAmount has value 0. May be VB.net work somewhat different that I do not know?
Edit:
It is kind of wierd that above mentioned statement is not returning value. The following statement is running absolutely fine.
Dim tmpVar As String() = dr.Item("Amount").ToString.Split(".")
Latest Edit:
I think it has become more wierd. The problem does not seem to be related with dr.Item("Amount"). Suppose I want to store the current culture value in a variable by following code,
Dim CultureInformation As String = System.Globalization.CultureInfo.CurrentCulture.DisplayName
Now CutlureInformation variable after the statement is executed contains "nothing" but the DisplayName has value of English (United States). So I think the problem is somewhere else.
You should be using this syntax:
Dim MyAmount As Double = dr.Field(Of Double)("Amount")
I am not sure why you are getting this behavior - your line should work too.
You can also try this:
Dim MyAmount As Double = DirectCast(dr.Item("Amount"), Double)
When facing a weird issue like this, always try various options to achieve the same result, do your research and compare the outputs. It greatly helps to answer a question on StackOverflow.

How do I convert from a string to an integer in Visual Basic?

How do I convert from a string to an integer? Here's what I tried:
Price = CInt(Int(txtPrice.Text))
I took out the Int and I still got an exception.
Use
Convert.toInt32(txtPrice.Text)
This is assuming VB.NET.
Judging by the name "txtPrice", you really don't want an Integer but a Decimal. So instead use:
Convert.toDecimal(txtPrice.Text)
If this is the case, be sure whatever you assign this to is Decimal not an Integer.
You can try it:
Dim Price As Integer
Int32.TryParse(txtPrice.Text, Price)
You can use the following to convert string to int:
CInt(String) for ints
CDec(String) for decimals
For details refer to Type Conversion Functions (Visual Basic).
Please try this, VB.NET 2010:
Integer.TryParse(txtPrice.Text, decPrice)
decPrice = Convert.ToInt32(txtPrice.Text)
From Mola Tshepo Kingsley (WWW.TUT.AC.ZA)
Convert.ToIntXX doesn't like being passed strings of decimals.
To be safe use
Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))
You can try these:
Dim valueStr as String = "10"
Dim valueIntConverted as Integer = CInt(valueStr)
Another example:
Dim newValueConverted as Integer = Val("100")
Use Val(txtPrice.text)
I would also allow only number and the dot char by inserting some validation code in the key press event of the price text box.
If there might be invalid characters in the textbox it will throw an exception. The Val command pulls numbers and strips invalid characters. It returns a double. So you want to convert the result of Val to whatever type you need.
Price = Convert.toInt32(Val(txtPrice.Text))
This will return 0 instead of throwing an error on invalid input. If that isn't desired you should be checking that the input is valid before you convert.

adding variables numical values (newb question)

Yesterday i had a look at how to set values of variables from nummbers stored in external txt files
the variables then needed to be added up so i used trial and error first
((XVAL) + (NEWVAL))
assuming that XVAL was set to 10 and NEWVAL was set to 20 i expected to get the answer of thirty but waqs presented with the new value of 10 20
VB.net pysicaly added the two values together but i wanted the mathematical product of the two which is ((10) + (20)) = 30
yep its a newb question could anyone explain how to achieve what im affter
XVAL and NEWVAL are strings, so they are simply being concatenated together. You need to convert them to integers, so that VB.NET will treat them as such. To do this, use the Int32.Parse() method.
Dim intXVAL As Integer = Int32.Parse(XVAL)
Dim intNEWVAL as Integer = Int32.Parse(NEWVAL)
Dim result = intXVAL + intNEWVAL
You want to cast them to a number first.
Try CDbl.
See http://msdn.microsoft.com/en-us/library/Aa263426 for more.
edit: Oops, thought you were talking about VBA.
Try using Double.Parse(YOURVALUE) if you're talking about VB.NET.
Have you tried the Val() function?
Val(XVAL) + Val(NEWVAL)
The + operator in VB.NET (for backwards-compatibility reasons) means both add and concatenate depending on the types of the variables it is being used with. With two numeric types (Integer, Single, Double, etc.), it adds the values together as you would expect. However, with String types, it concatenates the two strings.
Presumably, then, your XVAL and NEWVAL variables are String types because they're being read out of a text file, which is causing VB.NET to concatenate them into a new string instead of add them together. To get the behavior you're expecting, you need to convert them to numeric types.
Some of the other answers suggest casting simply casting the string values to numeric types (CInt, CSng, CDbl, etc.), but this may not work as expected if the value contained by your string cannot be converted to number. The Int32.Parse method will throw an exception if the value held by your string cannot be represented as a number. This is especially important to keep in mind if you're reading values from a text file that are not guaranteed to adhere to any particular constraints.
Instead, you probably want to use something like Int32.TryParse, which returns a Boolean value indicating whether or not the conversion succeeded and will not throw an exception.
As you are reading from a text file I assume that you are reading your values out as strings, so when you do this:
((XVAL) + (NEWVAL))
It is effectively concatenating the two strings together. In order to get the mathematical product of the two values these need to be int/integers which is the number type.
There are a number of ways you can do this, but in essence you have to 'cast' the strings to ints and then do your calculation.
So in vb.net it would be something like this (pseudo code):
Dim xval As String = "10"
Dim newval As String = "20"
Dim x As Integer = Int32.Parse(xval)
Dim n As Integer = Int32.Parse(newval)
Dim prod As Integer = x + n
Console.WriteLine(prod)
There are a number of other methods of doing this, for example using:
int.Parse(...)
or
Integer.TryParse(...)
More information on these sorts of type conversions can be found here:
http://dotnetperls.com/integer-parse-vbnet
One thing to bear in mind with these sorts of conversions is that you have to be certain that your input data is convertable. Otherwise your code will throw exceptions. This is where TryParse is useful as you can use this to check the inputs and handle invalid inputs without the need for exceptions.