我是编码和C#的新手,如果这是一个愚蠢的问题,我们深感抱歉。
我需要根据文本框(用户输入)重新定义变量,但出现错误
int age;
private void Age_TextChanged(object sender, EventArgs e)
{
//saves age in years
age = Age_TextChanged.int;
}
最佳答案
首先,错误消息试图指出您要求的内容不存在。作为补充信息,它还指出int
是关键字,不适合用作变量名。
如果您在文本框中输入了数字,并且想要该类型的变量中的等价整数,则需要使用Int32.TryParse()
尝试将该String
转换为Int32
。
采纳我的建议:更好地命名控件和变量。随着您的进步,它将使您的工作变得更加轻松。我已经对示例进行了调整:
Int32 iAge;
private void txtAge_TextChanged(Object sender, EventArgs e)
{
//Saves age in years...
if (!Int32.TryParse(txtAge.Text, out iAge))
{
MessageBox.Show(String.Format("Conversion of '{0}' to Int32 failed!", txtAge.Text), "Bad Data", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
//it parsed into the Int32, so do something with it...
}
}
https://stackoverflow.com/questions/28706839/