EN
Ce contenu n’est pas disponible dans votre langue. Voici la version anglaise.
Convert.ToByte Method (String)
May 02, 2013
Converts the specified String representation of a number to an equivalent 8-bit unsigned integer.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- value
- Type: System.String
A String containing a number to convert.
Return Value
Type: System.ByteAn 8-bit unsigned integer equivalent to the value of value.
-or-
Zero if value is null.
| Exception | Condition |
|---|---|
| FormatException | value does not consist of an optional sign followed by a sequence of digits (zero through nine). |
| OverflowException | value represents a number less than MinValue or greater than MaxValue. |
If you prefer not to handle an exception if the conversion fails, you can call the Byte.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.
The following code sample illustrates the use of ToByte, converting a String value to a Byte :
public void ConvertStringByte(string stringVal) { byte byteVal = 0; try { byteVal = System.Convert.ToByte(stringVal); outputBlock.Text += String.Format("{0} as a byte is: {1}", stringVal, byteVal) + "\n"; } catch (System.OverflowException) { outputBlock.Text += String.Format( "Conversion from string to byte overflowed.") + "\n"; } catch (System.FormatException) { outputBlock.Text += String.Format( "The string is not formatted as a byte.") + "\n"; } catch (System.ArgumentNullException) { outputBlock.Text += String.Format( "The string is null.") + "\n"; } //The conversion from byte to string is always valid. stringVal = System.Convert.ToString(byteVal); outputBlock.Text += String.Format("{0} as a string is {1}", byteVal, stringVal) + "\n"; }