Click here to Skip to main content
14,739,804 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
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
Updated 16-Jan-13 22:15pm
v5
Comments
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
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx

Hi,

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.

Thanks
   
v3
Comments
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.
[no name] 17-Jan-13 2:53am
   
Check my solution again. I have updated that again...
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.
[no name] 17-Jan-13 3:54am
   
BY then There must be some value which can't be converted to integer. Please check that by step by step execution.
fjdiewornncalwe 17-Jan-13 9:57am
   
My 1. The TryParse is the correct way to do this, it just needs to be written correctly.
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)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900