ProblemYou want to convert string data to several types of numeric or date/time variables in a consistent way. SolutionSample code folder: Chapter 05\ParseString Use the Parse() method provided by all types of variables in Visual Basic 2005. DiscussionThe Parse() method is the counterpart to each object's ToString() method. That is, the string created by calling an object's ToString() method will always be in a for-mat suitable for converting back to the same type of object using its Parse() method. A few examples can help clarify this: Dim doubleParse As Double = Double.Parse("3.1416") Dim ushortParse As UShort = UShort.Parse("65533") Dim dateParse As Date = Date.Parse("December 25, 2007") MsgBox(String.Format( _ "doubleParse: {0}{3}ushortParse: {1}{3}dateParse: {2}", _ doubleParse, ushortParse, dateParse, vbNewLine)) As shown in Figure 5-28, the data items are stored in the variables as expected when they are parsed. Figure 5-28. Converting string data to numeric and date/time formatsIn many cases, you might want to first check the string to make sure it can be parsed to the desired type of variable before making any attempt to do so. For example, use the IsDate() function to test a string to make sure it can be converted successfully before calling a Date variable's Parse() method to parse the date from the string. If the string is not convertible to the indicated data type, an exception will occur. See AlsoRecipe 5.22 discusses additional content-verification methods. |