Input string was not in a correct format The Next CEO of Stack OverflowHow to resolve “Input string was not in a correct format.” error?What is “'System.FormatException' occurred in mscorlib.dll but was not handled in user code”?Input string was not in a correct format in c#? Getting the exception as System.formatexception?An unhandled exception of type 'System.FormatException' Additional information: Input string was not in a correct formatThe input string was not in a correct formatInput String is not in Correct Format when reading DataTable valuesSubtraction from one Textfield to another got an errorError: Input string was not in the correct formatToInt32 throwing weird resultsDeleting row gives error “Input string was not in a correct format.”What is the difference between String and string in C#?What are the correct version numbers for C#?Case insensitive 'Contains(string)'manually input in textbox and connected to the serverDataset.GetChanges(DataRowState.Modified) return nullHow does a method in a winform listen to an event/delegate in App_Code, and not get a null event?C# from socket to mail slot in windowsC# How use sign from another window?Renaming a Field name by accepting values from textboxes…It shows "Unclosed quotation mark after the character string ''C# Directx App crashes in Release

Where to find order of arguments for default functions

How do I construct this japanese bowl?

Does the Brexit deal have to be agreed by both Houses?

Unreliable Magic - Is it worth it?

Term for the "extreme-extension" version of a straw man fallacy?

The King's new dress

Is a stroke of luck acceptable after a series of unfavorable events?

Are there languages with no euphemisms?

What is the point of a new vote on May's deal when the indicative votes suggest she will not win?

What makes a siege story/plot interesting?

How do we know the LHC results are robust?

Text adventure game code

Too much space between section and text in a twocolumn document

Why is there a PLL in CPU?

How to start emacs in "nothing" mode (`fundamental-mode`)

What is the difference between "behavior" and "behaviour"?

Is HostGator storing my password in plaintext?

How to safely derail a train during transit?

How long to clear the 'suck zone' of a turbofan after start is initiated?

Customer Requests (Sometimes) Drive Me Bonkers!

Trouble understanding the speech of overseas colleagues

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

Can a caster that cast Polymorph on themselves stop concentrating at any point even if their Int is low?

Why were Madagascar and New Zealand discovered so late?



Input string was not in a correct format



The Next CEO of Stack OverflowHow to resolve “Input string was not in a correct format.” error?What is “'System.FormatException' occurred in mscorlib.dll but was not handled in user code”?Input string was not in a correct format in c#? Getting the exception as System.formatexception?An unhandled exception of type 'System.FormatException' Additional information: Input string was not in a correct formatThe input string was not in a correct formatInput String is not in Correct Format when reading DataTable valuesSubtraction from one Textfield to another got an errorError: Input string was not in the correct formatToInt32 throwing weird resultsDeleting row gives error “Input string was not in a correct format.”What is the difference between String and string in C#?What are the correct version numbers for C#?Case insensitive 'Contains(string)'manually input in textbox and connected to the serverDataset.GetChanges(DataRowState.Modified) return nullHow does a method in a winform listen to an event/delegate in App_Code, and not get a null event?C# from socket to mail slot in windowsC# How use sign from another window?Renaming a Field name by accepting values from textboxes…It shows "Unclosed quotation mark after the character string ''C# Directx App crashes in Release










60















I'm new with C#, I have some basic knowledge in Java but I can't get this code to run properly.



It's just a basic calculator, but when I run the program VS2008 gives me this error:



Calculator



I did almost the same program but in java using JSwing and it worked perfectly.



Here's the form of c#:



Form



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace calculadorac
{
public partial class Form1 : Form


int a, b, c;
String resultado;

public Form1()

InitializeComponent();
a = Int32.Parse(textBox1.Text);
b = Int32.Parse(textBox2.Text);


private void button1_Click(object sender, EventArgs e)

add();
result();


private void button2_Click(object sender, EventArgs e)

substract();
result();


private void button3_Click(object sender, EventArgs e)

clear();


private void add()

c = a + b;
resultado = Convert.ToString(c);


private void substract()

c = a - b;
resultado = Convert.ToString(c);


private void result()

label1.Text = resultado;


private void clear()

label1.Text = "";
textBox1.Text = "";
textBox2.Text = "";




What can be the problem? Is there a way to solve it?



PS: I also tried



a = Convert.ToInt32(textBox1.text);
b = Convert.ToInt32(textBox2.text);


and it didn't work.










share|improve this question




























    60















    I'm new with C#, I have some basic knowledge in Java but I can't get this code to run properly.



    It's just a basic calculator, but when I run the program VS2008 gives me this error:



    Calculator



    I did almost the same program but in java using JSwing and it worked perfectly.



    Here's the form of c#:



    Form



    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace calculadorac
    {
    public partial class Form1 : Form


    int a, b, c;
    String resultado;

    public Form1()

    InitializeComponent();
    a = Int32.Parse(textBox1.Text);
    b = Int32.Parse(textBox2.Text);


    private void button1_Click(object sender, EventArgs e)

    add();
    result();


    private void button2_Click(object sender, EventArgs e)

    substract();
    result();


    private void button3_Click(object sender, EventArgs e)

    clear();


    private void add()

    c = a + b;
    resultado = Convert.ToString(c);


    private void substract()

    c = a - b;
    resultado = Convert.ToString(c);


    private void result()

    label1.Text = resultado;


    private void clear()

    label1.Text = "";
    textBox1.Text = "";
    textBox2.Text = "";




    What can be the problem? Is there a way to solve it?



    PS: I also tried



    a = Convert.ToInt32(textBox1.text);
    b = Convert.ToInt32(textBox2.text);


    and it didn't work.










    share|improve this question


























      60












      60








      60


      5






      I'm new with C#, I have some basic knowledge in Java but I can't get this code to run properly.



      It's just a basic calculator, but when I run the program VS2008 gives me this error:



      Calculator



      I did almost the same program but in java using JSwing and it worked perfectly.



      Here's the form of c#:



      Form



      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Windows.Forms;

      namespace calculadorac
      {
      public partial class Form1 : Form


      int a, b, c;
      String resultado;

      public Form1()

      InitializeComponent();
      a = Int32.Parse(textBox1.Text);
      b = Int32.Parse(textBox2.Text);


      private void button1_Click(object sender, EventArgs e)

      add();
      result();


      private void button2_Click(object sender, EventArgs e)

      substract();
      result();


      private void button3_Click(object sender, EventArgs e)

      clear();


      private void add()

      c = a + b;
      resultado = Convert.ToString(c);


      private void substract()

      c = a - b;
      resultado = Convert.ToString(c);


      private void result()

      label1.Text = resultado;


      private void clear()

      label1.Text = "";
      textBox1.Text = "";
      textBox2.Text = "";




      What can be the problem? Is there a way to solve it?



      PS: I also tried



      a = Convert.ToInt32(textBox1.text);
      b = Convert.ToInt32(textBox2.text);


      and it didn't work.










      share|improve this question
















      I'm new with C#, I have some basic knowledge in Java but I can't get this code to run properly.



      It's just a basic calculator, but when I run the program VS2008 gives me this error:



      Calculator



      I did almost the same program but in java using JSwing and it worked perfectly.



      Here's the form of c#:



      Form



      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Windows.Forms;

      namespace calculadorac
      {
      public partial class Form1 : Form


      int a, b, c;
      String resultado;

      public Form1()

      InitializeComponent();
      a = Int32.Parse(textBox1.Text);
      b = Int32.Parse(textBox2.Text);


      private void button1_Click(object sender, EventArgs e)

      add();
      result();


      private void button2_Click(object sender, EventArgs e)

      substract();
      result();


      private void button3_Click(object sender, EventArgs e)

      clear();


      private void add()

      c = a + b;
      resultado = Convert.ToString(c);


      private void substract()

      c = a - b;
      resultado = Convert.ToString(c);


      private void result()

      label1.Text = resultado;


      private void clear()

      label1.Text = "";
      textBox1.Text = "";
      textBox2.Text = "";




      What can be the problem? Is there a way to solve it?



      PS: I also tried



      a = Convert.ToInt32(textBox1.text);
      b = Convert.ToInt32(textBox2.text);


      and it didn't work.







      c# exception formatexception






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 11 '13 at 14:50









      Ian R. O'Brien

      3,86873667




      3,86873667










      asked Nov 30 '11 at 5:22









      kustomrtrkustomrtr

      5021612




      5021612






















          8 Answers
          8






          active

          oldest

          votes


















          91














          The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.



          It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a and b in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.






          share|improve this answer























          • This error message could be thrown also when try to Convert.ToDouble input comming from user with different cultureinfo, so you could use Convert.ToDouble (String, IFormatProvider) instead of just Convert.ToDouble (String). It is hard to debug, because program will work on you system, but will throw error on some of its users, this is why I have a method to log errors on my server and I found out for the problem fastly.

            – vinsa
            Apr 7 '18 at 14:24


















          44














          I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.



          I'd declared a string and was formatting it for use with JQTree which requires curly braces (). You have to use doubled curly braces for it to be accepted as a properly formatted string:



          string measurements = string.empty;
          measurements += string.Format(@"
          label: 'Measurement Name: 0',
          children: [
          label: 'Measured Value: 1',
          label: 'Min: 2',
          label: 'Max: 3',
          label: 'Measured String: 4',
          label: 'Expected String: 5',
          ]
          ,",
          drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
          drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
          drv["Min"] == null ? "NULL" : drv["Min"],
          drv["Max"] == null ? "NULL" : drv["Max"],
          drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
          drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);


          Hopefully this will help other folks who find this question but aren't parsing numerical data.






          share|improve this answer






























            16














            If you are not validating explicitly for numbers in the text field, in any case its better to use



            int result=0;
            if(int.TryParse(textBox1.Text,out result))


            Now if the result is success then you can proceed with your calculations.






            share|improve this answer


















            • 9





              Typically result doesn't need to be initialized.

              – yazanpro
              Feb 10 '15 at 21:05


















            7














            Problems



            There are some possible cases why the error occurs:



            1. Because textBox1.Text contains only number, but the number is too big/too small



            2. Because textBox1.Text contains:



              • a) non-number (except space in the beginning/end, - in the beginning) and/or

              • b) thousand separators in the applied culture for your code without specifying NumberStyles.AllowThousands or you specify NumberStyles.AllowThousands but put wrong thousand separator in the culture and/or

              • c) decimal separator (which should not exist in int parsing)



            NOT OK Examples:



            Case 1



            a = Int32.Parse("5000000000"); //5 billions, too large
            b = Int32.Parse("-5000000000"); //-5 billions, too small
            //The limit for int (32-bit integer) is only from -2,147,483,648 to 2,147,483,647


            Case 2 a)



            a = Int32.Parse("a189"); //having a 
            a = Int32.Parse("1-89"); //having - but not in the beginning
            a = Int32.Parse("18 9"); //having space, but not in the beginning or end


            Case 2 b)



            NumberStyles styles = NumberStyles.AllowThousands;
            a = Int32.Parse("1,189"); //not OK, no NumberStyles.AllowThousands
            b = Int32.Parse("1,189", styles, new CultureInfo("fr-FR")); //not OK, having NumberStyles.AllowThousands but the culture specified use different thousand separator


            Case 2 c)



            NumberStyles styles = NumberStyles.AllowDecimalPoint;
            a = Int32.Parse("1.189", styles); //wrong, int parse cannot parse decimal point at all!



            Seemingly NOT OK, but actually OK Examples:



            Case 2 a) OK



            a = Int32.Parse("-189"); //having - but in the beginning
            b = Int32.Parse(" 189 "); //having space, but in the beginning or end


            Case 2 b) OK



            NumberStyles styles = NumberStyles.AllowThousands;
            a = Int32.Parse("1,189", styles); //ok, having NumberStyles.AllowThousands in the correct culture
            b = Int32.Parse("1 189", styles, new CultureInfo("fr-FR")); //ok, having NumberStyles.AllowThousands and correct thousand separator is used for "fr-FR" culture



            Solutions



            In all cases, please check the value of textBox1.Text with your Visual Studio debugger and make sure that it has purely-acceptable numerical format for int range. Something like this:



            1234


            Also, you may consider of



            1. using TryParse instead of Parse to ensure that the non-parsed number does not cause you exception problem.


            2. check the result of TryParse and handle it if not true



              int val;
              bool result = int.TryParse(textbox1.Text, out val);
              if (!result)
              return; //something has gone wrong
              //OK, continue using val






            share|improve this answer
































              3














              You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.






              share|improve this answer






























                3














                In my case I forgot to put double curly brace to escape. myobject






                share|improve this answer






























                  0














                  it was my problem too ..
                  in my case i changed the PERSIAN number to LATIN number and it worked.
                  AND also trime your string before converting.



                  PersianCalendar pc = new PersianCalendar();
                  char[] seperator ='/';
                  string[] date = txtSaleDate.Text.Split(seperator);
                  int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());





                  share|improve this answer






























                    0














                    I had a similar problem that I solved with the following technique:



                    The exception was thrown at the following line of code (see the text decorated with ** below):



                    static void Main(string[] args)


                    double number = 0;
                    string numberStr = string.Format("0:C2", 100);

                    **number = Double.Parse(numberStr);**

                    Console.WriteLine("The number is 0", number);



                    After a bit of investigating, I realized that the problem was that the formatted string included a dollar sign ($) that the Parse/TryParse methods cannot resolve (i.e. - strip off). So using the Remove(...) method of the string object I changed the line to:



                    number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number


                    At that point the Parse(...) method worked as expected.






                    share|improve this answer





















                      protected by Community Sep 27 '17 at 16:25



                      Thank you for your interest in this question.
                      Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                      Would you like to answer one of these unanswered questions instead?














                      8 Answers
                      8






                      active

                      oldest

                      votes








                      8 Answers
                      8






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      91














                      The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.



                      It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a and b in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.






                      share|improve this answer























                      • This error message could be thrown also when try to Convert.ToDouble input comming from user with different cultureinfo, so you could use Convert.ToDouble (String, IFormatProvider) instead of just Convert.ToDouble (String). It is hard to debug, because program will work on you system, but will throw error on some of its users, this is why I have a method to log errors on my server and I found out for the problem fastly.

                        – vinsa
                        Apr 7 '18 at 14:24















                      91














                      The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.



                      It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a and b in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.






                      share|improve this answer























                      • This error message could be thrown also when try to Convert.ToDouble input comming from user with different cultureinfo, so you could use Convert.ToDouble (String, IFormatProvider) instead of just Convert.ToDouble (String). It is hard to debug, because program will work on you system, but will throw error on some of its users, this is why I have a method to log errors on my server and I found out for the problem fastly.

                        – vinsa
                        Apr 7 '18 at 14:24













                      91












                      91








                      91







                      The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.



                      It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a and b in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.






                      share|improve this answer













                      The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.



                      It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a and b in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 30 '11 at 5:24









                      JonJon

                      12.9k64453




                      12.9k64453












                      • This error message could be thrown also when try to Convert.ToDouble input comming from user with different cultureinfo, so you could use Convert.ToDouble (String, IFormatProvider) instead of just Convert.ToDouble (String). It is hard to debug, because program will work on you system, but will throw error on some of its users, this is why I have a method to log errors on my server and I found out for the problem fastly.

                        – vinsa
                        Apr 7 '18 at 14:24

















                      • This error message could be thrown also when try to Convert.ToDouble input comming from user with different cultureinfo, so you could use Convert.ToDouble (String, IFormatProvider) instead of just Convert.ToDouble (String). It is hard to debug, because program will work on you system, but will throw error on some of its users, this is why I have a method to log errors on my server and I found out for the problem fastly.

                        – vinsa
                        Apr 7 '18 at 14:24
















                      This error message could be thrown also when try to Convert.ToDouble input comming from user with different cultureinfo, so you could use Convert.ToDouble (String, IFormatProvider) instead of just Convert.ToDouble (String). It is hard to debug, because program will work on you system, but will throw error on some of its users, this is why I have a method to log errors on my server and I found out for the problem fastly.

                      – vinsa
                      Apr 7 '18 at 14:24





                      This error message could be thrown also when try to Convert.ToDouble input comming from user with different cultureinfo, so you could use Convert.ToDouble (String, IFormatProvider) instead of just Convert.ToDouble (String). It is hard to debug, because program will work on you system, but will throw error on some of its users, this is why I have a method to log errors on my server and I found out for the problem fastly.

                      – vinsa
                      Apr 7 '18 at 14:24













                      44














                      I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.



                      I'd declared a string and was formatting it for use with JQTree which requires curly braces (). You have to use doubled curly braces for it to be accepted as a properly formatted string:



                      string measurements = string.empty;
                      measurements += string.Format(@"
                      label: 'Measurement Name: 0',
                      children: [
                      label: 'Measured Value: 1',
                      label: 'Min: 2',
                      label: 'Max: 3',
                      label: 'Measured String: 4',
                      label: 'Expected String: 5',
                      ]
                      ,",
                      drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
                      drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
                      drv["Min"] == null ? "NULL" : drv["Min"],
                      drv["Max"] == null ? "NULL" : drv["Max"],
                      drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
                      drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);


                      Hopefully this will help other folks who find this question but aren't parsing numerical data.






                      share|improve this answer



























                        44














                        I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.



                        I'd declared a string and was formatting it for use with JQTree which requires curly braces (). You have to use doubled curly braces for it to be accepted as a properly formatted string:



                        string measurements = string.empty;
                        measurements += string.Format(@"
                        label: 'Measurement Name: 0',
                        children: [
                        label: 'Measured Value: 1',
                        label: 'Min: 2',
                        label: 'Max: 3',
                        label: 'Measured String: 4',
                        label: 'Expected String: 5',
                        ]
                        ,",
                        drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
                        drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
                        drv["Min"] == null ? "NULL" : drv["Min"],
                        drv["Max"] == null ? "NULL" : drv["Max"],
                        drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
                        drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);


                        Hopefully this will help other folks who find this question but aren't parsing numerical data.






                        share|improve this answer

























                          44












                          44








                          44







                          I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.



                          I'd declared a string and was formatting it for use with JQTree which requires curly braces (). You have to use doubled curly braces for it to be accepted as a properly formatted string:



                          string measurements = string.empty;
                          measurements += string.Format(@"
                          label: 'Measurement Name: 0',
                          children: [
                          label: 'Measured Value: 1',
                          label: 'Min: 2',
                          label: 'Max: 3',
                          label: 'Measured String: 4',
                          label: 'Expected String: 5',
                          ]
                          ,",
                          drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
                          drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
                          drv["Min"] == null ? "NULL" : drv["Min"],
                          drv["Max"] == null ? "NULL" : drv["Max"],
                          drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
                          drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);


                          Hopefully this will help other folks who find this question but aren't parsing numerical data.






                          share|improve this answer













                          I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.



                          I'd declared a string and was formatting it for use with JQTree which requires curly braces (). You have to use doubled curly braces for it to be accepted as a properly formatted string:



                          string measurements = string.empty;
                          measurements += string.Format(@"
                          label: 'Measurement Name: 0',
                          children: [
                          label: 'Measured Value: 1',
                          label: 'Min: 2',
                          label: 'Max: 3',
                          label: 'Measured String: 4',
                          label: 'Expected String: 5',
                          ]
                          ,",
                          drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
                          drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
                          drv["Min"] == null ? "NULL" : drv["Min"],
                          drv["Max"] == null ? "NULL" : drv["Max"],
                          drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
                          drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);


                          Hopefully this will help other folks who find this question but aren't parsing numerical data.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Oct 23 '14 at 16:01









                          delliottgdelliottg

                          2,39012641




                          2,39012641





















                              16














                              If you are not validating explicitly for numbers in the text field, in any case its better to use



                              int result=0;
                              if(int.TryParse(textBox1.Text,out result))


                              Now if the result is success then you can proceed with your calculations.






                              share|improve this answer


















                              • 9





                                Typically result doesn't need to be initialized.

                                – yazanpro
                                Feb 10 '15 at 21:05















                              16














                              If you are not validating explicitly for numbers in the text field, in any case its better to use



                              int result=0;
                              if(int.TryParse(textBox1.Text,out result))


                              Now if the result is success then you can proceed with your calculations.






                              share|improve this answer


















                              • 9





                                Typically result doesn't need to be initialized.

                                – yazanpro
                                Feb 10 '15 at 21:05













                              16












                              16








                              16







                              If you are not validating explicitly for numbers in the text field, in any case its better to use



                              int result=0;
                              if(int.TryParse(textBox1.Text,out result))


                              Now if the result is success then you can proceed with your calculations.






                              share|improve this answer













                              If you are not validating explicitly for numbers in the text field, in any case its better to use



                              int result=0;
                              if(int.TryParse(textBox1.Text,out result))


                              Now if the result is success then you can proceed with your calculations.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 30 '11 at 5:30









                              V4VendettaV4Vendetta

                              29k66477




                              29k66477







                              • 9





                                Typically result doesn't need to be initialized.

                                – yazanpro
                                Feb 10 '15 at 21:05












                              • 9





                                Typically result doesn't need to be initialized.

                                – yazanpro
                                Feb 10 '15 at 21:05







                              9




                              9





                              Typically result doesn't need to be initialized.

                              – yazanpro
                              Feb 10 '15 at 21:05





                              Typically result doesn't need to be initialized.

                              – yazanpro
                              Feb 10 '15 at 21:05











                              7














                              Problems



                              There are some possible cases why the error occurs:



                              1. Because textBox1.Text contains only number, but the number is too big/too small



                              2. Because textBox1.Text contains:



                                • a) non-number (except space in the beginning/end, - in the beginning) and/or

                                • b) thousand separators in the applied culture for your code without specifying NumberStyles.AllowThousands or you specify NumberStyles.AllowThousands but put wrong thousand separator in the culture and/or

                                • c) decimal separator (which should not exist in int parsing)



                              NOT OK Examples:



                              Case 1



                              a = Int32.Parse("5000000000"); //5 billions, too large
                              b = Int32.Parse("-5000000000"); //-5 billions, too small
                              //The limit for int (32-bit integer) is only from -2,147,483,648 to 2,147,483,647


                              Case 2 a)



                              a = Int32.Parse("a189"); //having a 
                              a = Int32.Parse("1-89"); //having - but not in the beginning
                              a = Int32.Parse("18 9"); //having space, but not in the beginning or end


                              Case 2 b)



                              NumberStyles styles = NumberStyles.AllowThousands;
                              a = Int32.Parse("1,189"); //not OK, no NumberStyles.AllowThousands
                              b = Int32.Parse("1,189", styles, new CultureInfo("fr-FR")); //not OK, having NumberStyles.AllowThousands but the culture specified use different thousand separator


                              Case 2 c)



                              NumberStyles styles = NumberStyles.AllowDecimalPoint;
                              a = Int32.Parse("1.189", styles); //wrong, int parse cannot parse decimal point at all!



                              Seemingly NOT OK, but actually OK Examples:



                              Case 2 a) OK



                              a = Int32.Parse("-189"); //having - but in the beginning
                              b = Int32.Parse(" 189 "); //having space, but in the beginning or end


                              Case 2 b) OK



                              NumberStyles styles = NumberStyles.AllowThousands;
                              a = Int32.Parse("1,189", styles); //ok, having NumberStyles.AllowThousands in the correct culture
                              b = Int32.Parse("1 189", styles, new CultureInfo("fr-FR")); //ok, having NumberStyles.AllowThousands and correct thousand separator is used for "fr-FR" culture



                              Solutions



                              In all cases, please check the value of textBox1.Text with your Visual Studio debugger and make sure that it has purely-acceptable numerical format for int range. Something like this:



                              1234


                              Also, you may consider of



                              1. using TryParse instead of Parse to ensure that the non-parsed number does not cause you exception problem.


                              2. check the result of TryParse and handle it if not true



                                int val;
                                bool result = int.TryParse(textbox1.Text, out val);
                                if (!result)
                                return; //something has gone wrong
                                //OK, continue using val






                              share|improve this answer





























                                7














                                Problems



                                There are some possible cases why the error occurs:



                                1. Because textBox1.Text contains only number, but the number is too big/too small



                                2. Because textBox1.Text contains:



                                  • a) non-number (except space in the beginning/end, - in the beginning) and/or

                                  • b) thousand separators in the applied culture for your code without specifying NumberStyles.AllowThousands or you specify NumberStyles.AllowThousands but put wrong thousand separator in the culture and/or

                                  • c) decimal separator (which should not exist in int parsing)



                                NOT OK Examples:



                                Case 1



                                a = Int32.Parse("5000000000"); //5 billions, too large
                                b = Int32.Parse("-5000000000"); //-5 billions, too small
                                //The limit for int (32-bit integer) is only from -2,147,483,648 to 2,147,483,647


                                Case 2 a)



                                a = Int32.Parse("a189"); //having a 
                                a = Int32.Parse("1-89"); //having - but not in the beginning
                                a = Int32.Parse("18 9"); //having space, but not in the beginning or end


                                Case 2 b)



                                NumberStyles styles = NumberStyles.AllowThousands;
                                a = Int32.Parse("1,189"); //not OK, no NumberStyles.AllowThousands
                                b = Int32.Parse("1,189", styles, new CultureInfo("fr-FR")); //not OK, having NumberStyles.AllowThousands but the culture specified use different thousand separator


                                Case 2 c)



                                NumberStyles styles = NumberStyles.AllowDecimalPoint;
                                a = Int32.Parse("1.189", styles); //wrong, int parse cannot parse decimal point at all!



                                Seemingly NOT OK, but actually OK Examples:



                                Case 2 a) OK



                                a = Int32.Parse("-189"); //having - but in the beginning
                                b = Int32.Parse(" 189 "); //having space, but in the beginning or end


                                Case 2 b) OK



                                NumberStyles styles = NumberStyles.AllowThousands;
                                a = Int32.Parse("1,189", styles); //ok, having NumberStyles.AllowThousands in the correct culture
                                b = Int32.Parse("1 189", styles, new CultureInfo("fr-FR")); //ok, having NumberStyles.AllowThousands and correct thousand separator is used for "fr-FR" culture



                                Solutions



                                In all cases, please check the value of textBox1.Text with your Visual Studio debugger and make sure that it has purely-acceptable numerical format for int range. Something like this:



                                1234


                                Also, you may consider of



                                1. using TryParse instead of Parse to ensure that the non-parsed number does not cause you exception problem.


                                2. check the result of TryParse and handle it if not true



                                  int val;
                                  bool result = int.TryParse(textbox1.Text, out val);
                                  if (!result)
                                  return; //something has gone wrong
                                  //OK, continue using val






                                share|improve this answer



























                                  7












                                  7








                                  7







                                  Problems



                                  There are some possible cases why the error occurs:



                                  1. Because textBox1.Text contains only number, but the number is too big/too small



                                  2. Because textBox1.Text contains:



                                    • a) non-number (except space in the beginning/end, - in the beginning) and/or

                                    • b) thousand separators in the applied culture for your code without specifying NumberStyles.AllowThousands or you specify NumberStyles.AllowThousands but put wrong thousand separator in the culture and/or

                                    • c) decimal separator (which should not exist in int parsing)



                                  NOT OK Examples:



                                  Case 1



                                  a = Int32.Parse("5000000000"); //5 billions, too large
                                  b = Int32.Parse("-5000000000"); //-5 billions, too small
                                  //The limit for int (32-bit integer) is only from -2,147,483,648 to 2,147,483,647


                                  Case 2 a)



                                  a = Int32.Parse("a189"); //having a 
                                  a = Int32.Parse("1-89"); //having - but not in the beginning
                                  a = Int32.Parse("18 9"); //having space, but not in the beginning or end


                                  Case 2 b)



                                  NumberStyles styles = NumberStyles.AllowThousands;
                                  a = Int32.Parse("1,189"); //not OK, no NumberStyles.AllowThousands
                                  b = Int32.Parse("1,189", styles, new CultureInfo("fr-FR")); //not OK, having NumberStyles.AllowThousands but the culture specified use different thousand separator


                                  Case 2 c)



                                  NumberStyles styles = NumberStyles.AllowDecimalPoint;
                                  a = Int32.Parse("1.189", styles); //wrong, int parse cannot parse decimal point at all!



                                  Seemingly NOT OK, but actually OK Examples:



                                  Case 2 a) OK



                                  a = Int32.Parse("-189"); //having - but in the beginning
                                  b = Int32.Parse(" 189 "); //having space, but in the beginning or end


                                  Case 2 b) OK



                                  NumberStyles styles = NumberStyles.AllowThousands;
                                  a = Int32.Parse("1,189", styles); //ok, having NumberStyles.AllowThousands in the correct culture
                                  b = Int32.Parse("1 189", styles, new CultureInfo("fr-FR")); //ok, having NumberStyles.AllowThousands and correct thousand separator is used for "fr-FR" culture



                                  Solutions



                                  In all cases, please check the value of textBox1.Text with your Visual Studio debugger and make sure that it has purely-acceptable numerical format for int range. Something like this:



                                  1234


                                  Also, you may consider of



                                  1. using TryParse instead of Parse to ensure that the non-parsed number does not cause you exception problem.


                                  2. check the result of TryParse and handle it if not true



                                    int val;
                                    bool result = int.TryParse(textbox1.Text, out val);
                                    if (!result)
                                    return; //something has gone wrong
                                    //OK, continue using val






                                  share|improve this answer















                                  Problems



                                  There are some possible cases why the error occurs:



                                  1. Because textBox1.Text contains only number, but the number is too big/too small



                                  2. Because textBox1.Text contains:



                                    • a) non-number (except space in the beginning/end, - in the beginning) and/or

                                    • b) thousand separators in the applied culture for your code without specifying NumberStyles.AllowThousands or you specify NumberStyles.AllowThousands but put wrong thousand separator in the culture and/or

                                    • c) decimal separator (which should not exist in int parsing)



                                  NOT OK Examples:



                                  Case 1



                                  a = Int32.Parse("5000000000"); //5 billions, too large
                                  b = Int32.Parse("-5000000000"); //-5 billions, too small
                                  //The limit for int (32-bit integer) is only from -2,147,483,648 to 2,147,483,647


                                  Case 2 a)



                                  a = Int32.Parse("a189"); //having a 
                                  a = Int32.Parse("1-89"); //having - but not in the beginning
                                  a = Int32.Parse("18 9"); //having space, but not in the beginning or end


                                  Case 2 b)



                                  NumberStyles styles = NumberStyles.AllowThousands;
                                  a = Int32.Parse("1,189"); //not OK, no NumberStyles.AllowThousands
                                  b = Int32.Parse("1,189", styles, new CultureInfo("fr-FR")); //not OK, having NumberStyles.AllowThousands but the culture specified use different thousand separator


                                  Case 2 c)



                                  NumberStyles styles = NumberStyles.AllowDecimalPoint;
                                  a = Int32.Parse("1.189", styles); //wrong, int parse cannot parse decimal point at all!



                                  Seemingly NOT OK, but actually OK Examples:



                                  Case 2 a) OK



                                  a = Int32.Parse("-189"); //having - but in the beginning
                                  b = Int32.Parse(" 189 "); //having space, but in the beginning or end


                                  Case 2 b) OK



                                  NumberStyles styles = NumberStyles.AllowThousands;
                                  a = Int32.Parse("1,189", styles); //ok, having NumberStyles.AllowThousands in the correct culture
                                  b = Int32.Parse("1 189", styles, new CultureInfo("fr-FR")); //ok, having NumberStyles.AllowThousands and correct thousand separator is used for "fr-FR" culture



                                  Solutions



                                  In all cases, please check the value of textBox1.Text with your Visual Studio debugger and make sure that it has purely-acceptable numerical format for int range. Something like this:



                                  1234


                                  Also, you may consider of



                                  1. using TryParse instead of Parse to ensure that the non-parsed number does not cause you exception problem.


                                  2. check the result of TryParse and handle it if not true



                                    int val;
                                    bool result = int.TryParse(textbox1.Text, out val);
                                    if (!result)
                                    return; //something has gone wrong
                                    //OK, continue using val







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited May 23 '17 at 12:10









                                  Community

                                  11




                                  11










                                  answered Apr 19 '16 at 8:21









                                  IanIan

                                  25.4k144978




                                  25.4k144978





















                                      3














                                      You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.






                                      share|improve this answer



























                                        3














                                        You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.






                                        share|improve this answer

























                                          3












                                          3








                                          3







                                          You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.






                                          share|improve this answer













                                          You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Nov 30 '11 at 5:29









                                          Kirtan PandyaKirtan Pandya

                                          1336




                                          1336





















                                              3














                                              In my case I forgot to put double curly brace to escape. myobject






                                              share|improve this answer



























                                                3














                                                In my case I forgot to put double curly brace to escape. myobject






                                                share|improve this answer

























                                                  3












                                                  3








                                                  3







                                                  In my case I forgot to put double curly brace to escape. myobject






                                                  share|improve this answer













                                                  In my case I forgot to put double curly brace to escape. myobject







                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Jan 23 '18 at 14:25









                                                  zawhtutzawhtut

                                                  6,29043967




                                                  6,29043967





















                                                      0














                                                      it was my problem too ..
                                                      in my case i changed the PERSIAN number to LATIN number and it worked.
                                                      AND also trime your string before converting.



                                                      PersianCalendar pc = new PersianCalendar();
                                                      char[] seperator ='/';
                                                      string[] date = txtSaleDate.Text.Split(seperator);
                                                      int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());





                                                      share|improve this answer



























                                                        0














                                                        it was my problem too ..
                                                        in my case i changed the PERSIAN number to LATIN number and it worked.
                                                        AND also trime your string before converting.



                                                        PersianCalendar pc = new PersianCalendar();
                                                        char[] seperator ='/';
                                                        string[] date = txtSaleDate.Text.Split(seperator);
                                                        int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());





                                                        share|improve this answer

























                                                          0












                                                          0








                                                          0







                                                          it was my problem too ..
                                                          in my case i changed the PERSIAN number to LATIN number and it worked.
                                                          AND also trime your string before converting.



                                                          PersianCalendar pc = new PersianCalendar();
                                                          char[] seperator ='/';
                                                          string[] date = txtSaleDate.Text.Split(seperator);
                                                          int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());





                                                          share|improve this answer













                                                          it was my problem too ..
                                                          in my case i changed the PERSIAN number to LATIN number and it worked.
                                                          AND also trime your string before converting.



                                                          PersianCalendar pc = new PersianCalendar();
                                                          char[] seperator ='/';
                                                          string[] date = txtSaleDate.Text.Split(seperator);
                                                          int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Dec 10 '15 at 14:54









                                                          afshinafshin

                                                          2629




                                                          2629





















                                                              0














                                                              I had a similar problem that I solved with the following technique:



                                                              The exception was thrown at the following line of code (see the text decorated with ** below):



                                                              static void Main(string[] args)


                                                              double number = 0;
                                                              string numberStr = string.Format("0:C2", 100);

                                                              **number = Double.Parse(numberStr);**

                                                              Console.WriteLine("The number is 0", number);



                                                              After a bit of investigating, I realized that the problem was that the formatted string included a dollar sign ($) that the Parse/TryParse methods cannot resolve (i.e. - strip off). So using the Remove(...) method of the string object I changed the line to:



                                                              number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number


                                                              At that point the Parse(...) method worked as expected.






                                                              share|improve this answer



























                                                                0














                                                                I had a similar problem that I solved with the following technique:



                                                                The exception was thrown at the following line of code (see the text decorated with ** below):



                                                                static void Main(string[] args)


                                                                double number = 0;
                                                                string numberStr = string.Format("0:C2", 100);

                                                                **number = Double.Parse(numberStr);**

                                                                Console.WriteLine("The number is 0", number);



                                                                After a bit of investigating, I realized that the problem was that the formatted string included a dollar sign ($) that the Parse/TryParse methods cannot resolve (i.e. - strip off). So using the Remove(...) method of the string object I changed the line to:



                                                                number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number


                                                                At that point the Parse(...) method worked as expected.






                                                                share|improve this answer

























                                                                  0












                                                                  0








                                                                  0







                                                                  I had a similar problem that I solved with the following technique:



                                                                  The exception was thrown at the following line of code (see the text decorated with ** below):



                                                                  static void Main(string[] args)


                                                                  double number = 0;
                                                                  string numberStr = string.Format("0:C2", 100);

                                                                  **number = Double.Parse(numberStr);**

                                                                  Console.WriteLine("The number is 0", number);



                                                                  After a bit of investigating, I realized that the problem was that the formatted string included a dollar sign ($) that the Parse/TryParse methods cannot resolve (i.e. - strip off). So using the Remove(...) method of the string object I changed the line to:



                                                                  number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number


                                                                  At that point the Parse(...) method worked as expected.






                                                                  share|improve this answer













                                                                  I had a similar problem that I solved with the following technique:



                                                                  The exception was thrown at the following line of code (see the text decorated with ** below):



                                                                  static void Main(string[] args)


                                                                  double number = 0;
                                                                  string numberStr = string.Format("0:C2", 100);

                                                                  **number = Double.Parse(numberStr);**

                                                                  Console.WriteLine("The number is 0", number);



                                                                  After a bit of investigating, I realized that the problem was that the formatted string included a dollar sign ($) that the Parse/TryParse methods cannot resolve (i.e. - strip off). So using the Remove(...) method of the string object I changed the line to:



                                                                  number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number


                                                                  At that point the Parse(...) method worked as expected.







                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Jun 7 '18 at 16:51









                                                                  astevens009astevens009

                                                                  103




                                                                  103















                                                                      protected by Community Sep 27 '17 at 16:25



                                                                      Thank you for your interest in this question.
                                                                      Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                      Would you like to answer one of these unanswered questions instead?



                                                                      Popular posts from this blog

                                                                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                                                                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                                                                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme