You can use the overloaded TryParse() , which adds the NumberStyle parameter to the TryParse call, which provides parsing of hexadecimal values. Use NumberStyles.HexNumber , which allows you to pass a string as a hexadecimal number.
Note The problem with NumberStyles.HexNumber is that it does not support parsing values with a prefix (i.e. 0x , &H or # ), so you have to disable it before trying to parse the value.
Basically you would do this:
uint color; var hex = TextBox1.Text; if (hex.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase) || hex.StartsWith("&H", StringComparison.CurrentCultureIgnoreCase)) { hex = hex.Substring(2); } bool parsedSuccessfully = uint.TryParse(hex, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out color);
See this article for an example of how to use the NumberStyles enumeration: http://msdn.microsoft.com/en-us/library/zf50za27.aspx
Jeremy Wiebe Sep 19 '08 at 1:19 2008-09-19 01:19
source share