I'm new with C#, I have some basic knowledge in Java but I can't get this code to run properly.
我是c#的新手,我有一些Java的基本知识,但是我不能让代码正常运行。
It's just a basic calculator, but when I run the program VS2008 gives me this error:
它只是一个基本的计算器,但是当我运行程序VS2008给我这个错误:
I did almost the same program but in java using JSwing and it worked perfectly.
我做了几乎相同的程序,但在java中使用JSwing,效果非常好。
Here's the form of c#:
这是c#的形式:
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
PS:我也试过了
a = Convert.ToInt32(textBox1.text);
b = Convert.ToInt32(textBox2.text);
and it didn't work.
和它没有工作。
7 个解决方案
#1
74
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.
当表单被创建时,文本框会立即包含一个有效的整数,这是非常不可能的——这就是您获取整型值的地方。在按钮单击事件中更新a和b会更有意义(就像在构造函数中一样)。tryparse方法——如果字符串实际上不包含一个整数,那么它就更容易使用——它不会抛出异常,因此更容易恢复。
#2
36
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.
我遇到了这个例外,除了它与解析数值输入无关。所以这不是OP的问题的答案,但我认为分享知识是可以接受的。
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:
我声明了一个字符串,并将它格式化为JQTree,它需要花括号({})。您必须使用加倍的花括号才能被接受为一个格式正确的字符串:
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.
希望这能帮助其他找到这个问题的人,而不是解析数字数据。
#3
13
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.
如果结果是成功的,那么你就可以继续计算了。
#4
4
Problems
问题
There are some possible cases why the error occurs:
有一些可能的情况为什么会出现错误:
-
Because
textBox1.Text
contains only number, but the number is too big/too small因为textBox1。文本只包含数字,但数字太大/太小。
-
Because
textBox1.Text
contains:因为textBox1。文本包含:
- a) non-number (except
space
in the beginning/end,-
in the beginning) and/or - a)非数字(开始/结尾的空格,在开头)和/或。
- b) thousand separators in the applied culture for your code without specifying
NumberStyles.AllowThousands
or you specifyNumberStyles.AllowThousands
but put wrongthousand separator
in the culture and/or - b)在你的代码应用文化中有上千个分隔符,没有指定数字样式。允许数千或指定NumberStyles。允许数千人,但在文化和/或。
- c) decimal separator (which should not exist in
int
parsing) - c)十进制分隔符(不应该存在于int解析中)
- a) non-number (except
NOT OK Examples:
没有好的例子:
Case 1
案例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)
例2)
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)
例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)
例2摄氏度)
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
例2)好
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
例2 b)好
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:
在所有情况下,请检查textBox1的值。文本与您的visualstudio调试器,并确保它在int范围内具有可接受的数字格式。是这样的:
1234
Also, you may consider of
你也可以考虑一下。
- using
TryParse
instead ofParse
to ensure that the non-parsed number does not cause you exception problem. - 使用TryParse而不是Parse来确保非解析数字不会导致异常问题。
-
check the result of
TryParse
and handle it if nottrue
检查TryParse的结果,如果不正确,则处理它。
int val; bool result = int.TryParse(textbox1.Text, out val); if (!result) return; //something has gone wrong //OK, continue using val
#5
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.
您没有提到如果您的文本框在设计时或现在有值。当窗体初始化时,如果在表单设计时没有将文本框放入文本框中,则可能没有值。您可以通过在desgin中设置文本属性来将int值放在表单设计中,这样就可以工作了。
#6
1
In my case I forgot to put double curly brace to escape. {{myobject}}
在我的例子中,我忘了把双花括号放出来。{ { myobject } }
#7
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.
这也是我的问题。在我的例子中,我把波斯数字换成了拉丁数字,它起作用了。在转换之前,也要把你的字符串trime。
PersianCalendar pc = new PersianCalendar();
char[] seperator ={'/'};
string[] date = txtSaleDate.Text.Split(seperator);
int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());
#1
74
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.
当表单被创建时,文本框会立即包含一个有效的整数,这是非常不可能的——这就是您获取整型值的地方。在按钮单击事件中更新a和b会更有意义(就像在构造函数中一样)。tryparse方法——如果字符串实际上不包含一个整数,那么它就更容易使用——它不会抛出异常,因此更容易恢复。
#2
36
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.
我遇到了这个例外,除了它与解析数值输入无关。所以这不是OP的问题的答案,但我认为分享知识是可以接受的。
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:
我声明了一个字符串,并将它格式化为JQTree,它需要花括号({})。您必须使用加倍的花括号才能被接受为一个格式正确的字符串:
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.
希望这能帮助其他找到这个问题的人,而不是解析数字数据。
#3
13
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.
如果结果是成功的,那么你就可以继续计算了。
#4
4
Problems
问题
There are some possible cases why the error occurs:
有一些可能的情况为什么会出现错误:
-
Because
textBox1.Text
contains only number, but the number is too big/too small因为textBox1。文本只包含数字,但数字太大/太小。
-
Because
textBox1.Text
contains:因为textBox1。文本包含:
- a) non-number (except
space
in the beginning/end,-
in the beginning) and/or - a)非数字(开始/结尾的空格,在开头)和/或。
- b) thousand separators in the applied culture for your code without specifying
NumberStyles.AllowThousands
or you specifyNumberStyles.AllowThousands
but put wrongthousand separator
in the culture and/or - b)在你的代码应用文化中有上千个分隔符,没有指定数字样式。允许数千或指定NumberStyles。允许数千人,但在文化和/或。
- c) decimal separator (which should not exist in
int
parsing) - c)十进制分隔符(不应该存在于int解析中)
- a) non-number (except
NOT OK Examples:
没有好的例子:
Case 1
案例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)
例2)
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)
例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)
例2摄氏度)
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
例2)好
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
例2 b)好
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:
在所有情况下,请检查textBox1的值。文本与您的visualstudio调试器,并确保它在int范围内具有可接受的数字格式。是这样的:
1234
Also, you may consider of
你也可以考虑一下。
- using
TryParse
instead ofParse
to ensure that the non-parsed number does not cause you exception problem. - 使用TryParse而不是Parse来确保非解析数字不会导致异常问题。
-
check the result of
TryParse
and handle it if nottrue
检查TryParse的结果,如果不正确,则处理它。
int val; bool result = int.TryParse(textbox1.Text, out val); if (!result) return; //something has gone wrong //OK, continue using val
#5
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.
您没有提到如果您的文本框在设计时或现在有值。当窗体初始化时,如果在表单设计时没有将文本框放入文本框中,则可能没有值。您可以通过在desgin中设置文本属性来将int值放在表单设计中,这样就可以工作了。
#6
1
In my case I forgot to put double curly brace to escape. {{myobject}}
在我的例子中,我忘了把双花括号放出来。{ { myobject } }
#7
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.
这也是我的问题。在我的例子中,我把波斯数字换成了拉丁数字,它起作用了。在转换之前,也要把你的字符串trime。
PersianCalendar pc = new PersianCalendar();
char[] seperator ={'/'};
string[] date = txtSaleDate.Text.Split(seperator);
int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());