Click here to Skip to main content
11,934,443 members (41,704 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# string
Actually i am getting substrings like 19 or sometimes 1A.

I am taking substring and converting it to a Integer. For displaying in richtextbox i am converting it to a string.

I get errors after getting some correct values.

error : Input String is not a correct format.

private void DisplayData(MessageType type, string msg)
          richTextBox1.Invoke(new EventHandler(delegate
               string substring = string.Empty;
               if (msg.Length > 57)
               substring = msg.Substring(54, 2);
     int decValue =int.Parse(substring,System.Globalization.NumberStyles.HexNumber);
               string hexValue = decValue.ToString();
               richTextBox1.AppendText(hexValue) ;
Posted 16-Jan-13 21:29pm
Edited 16-Jan-13 22:15pm
CPallini 17-Jan-13 3:36am
You should check with the debugger the value of the string, when the error happens.
ontheline89 17-Jan-13 3:39am
yes the format of values changer after some time, you can say some garbage values. Is there any way that it just convert only strings which are in format and discard other without getting any errors.
CPallini 17-Jan-13 3:55am
Yes, handle the exception (with catch) or use TryParse method, see
Rate this: bad
Please Sign up or sign in to vote.

Solution 1


use like this:

int decValue = int.TryParse(substring,decValue);// This will not even compile since TryParse returns a bool not an int.

To convert hexadecimal values to integer use:

int decValue = int.Parse(substring, System.Globalization.NumberStyles.HexNumber);

You may be getting error for "1A". Try to avoid those values.

ontheline89 17-Jan-13 2:44am
I cant avoid values like 1A OR 1B.
These are HEXADECIMAL values and i need to convert them to integers.
I am still getting errors.
ontheline89 17-Jan-13 2:56am
i am getting correct values, but after 4 to 5 values, i get error that
Input Sting was not in a correct format.
Marcus Kramer 17-Jan-13 9:57am
My 1. The TryParse is the correct way to do this, it just needs to be written correctly.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

int decValue;
if( !int.TryParse(substring, out decValue) )
   // Set a default value to decValue in case the parse fails.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web03 | 2.8.151126.1 | Last Updated 17 Jan 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100