ToBoolean Method (String)

Convert.ToBoolean Method (String)

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

Converts the specified String representation of a logical value to its Boolean equivalent.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
Public Shared Function ToBoolean ( _
	value As String _
) As Boolean

Parameters

value
Type: System.String
A String that contains the value of either TrueString or FalseString.

Return Value

Type: System.Boolean
true if value equals TrueString, or false if value equals FalseString or Nothing.

ExceptionCondition
FormatException

value is not equal to TrueString or FalseString.

For a successful conversion to occur, the value parameter must equal either Boolean.TrueString, a string constant whose value is True, Boolean.FalseString, a string constant whose value is False, or it must be Nothing. In comparing value with Boolean.TrueString and Boolean.FalseString, the method ignores case as well as leading and trailing white space.

If you prefer not to handle an exception if the conversion fails, you can call the Boolean.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.

The following example uses the Convert.ToBoolean(String) method to convert various strings to Boolean values.


Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      ConvertToBoolean(outputBlock, Nothing)
      ConvertToBoolean(outputBlock, String.Empty)
      ConvertToBoolean(outputBlock, "true")
      ConvertToBoolean(outputBlock, "TrueString")
      ConvertToBoolean(outputBlock, "False")
      ConvertToBoolean(outputBlock, "    false    ")
      ConvertToBoolean(outputBlock, "-1")
      ConvertToBoolean(outputBlock, "0")
   End Sub

   Private Sub ConvertToBoolean(ByVal outputBlock As System.Windows.Controls.TextBlock, ByVal value As String)
      Try
         outputBlock.Text += String.Format("Converted '{0}' to {1}.", value, _
                           Convert.ToBoolean(value)) & vbCrLf
      Catch e As FormatException
         outputBlock.Text += String.Format("Unable to convert '{0}' to a Boolean.", value) & vbCrLf
      End Try
   End Sub
End Module
' The example displays the following output:
'       Converted '' to False.
'       Unable to convert '' to a Boolean.
'       Converted 'true' to True.
'       Unable to convert 'TrueString' to a Boolean.
'       Converted 'False' to False.
'       Converted '    false    ' to False.
'       Unable to convert '-1' to a Boolean.
'       Unable to convert '0' to a Boolean.


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2017 Microsoft