C# 从文本框中获取整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11931770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get integer from Textbox
提问by
I am very new to C# and this question might sound very stupid. I wonder how I'm going get the integer(user's input) from the textBox1and use it in if else statement?
我对 C# 很陌生,这个问题可能听起来很愚蠢。我想知道如何从 中获取整数(用户的输入)textBox1并在 if else 语句中使用它?
Please give some examples
请举几个例子
采纳答案by Habib
You need to parse the value of textbox.Textwhich is a string to intvalue. You may use int.TryParse, or int.Parseor Convert.ToInt32.
您需要将textbox.Text字符串解析为int值。您可以使用int.TryParse,或int.Parse或Convert.ToInt32。
TextBox.Textproperty is of stringtype. You may look at the following sample code.
TextBox.Text属性是string类型。您可以查看以下示例代码。
int.TryParse
int.TryParse
This will return true if the parsing is successful and false if it fails.
如果解析成功,这将返回 true,如果解析失败,则返回 false。
int value;
if(int.TryParse(textBox1.Text,out value))
{
//parsing successful
}
else
{
//parsing failed.
}
Convert.ToInt32
Convert.ToInt32
This may throw an exception if the parsing is unsuccessful.
如果解析不成功,这可能会引发异常。
int value = Convert.ToInt32(textBox1.Text);
int.Parse
解析
int value = int.Parse(textBox1.Text);
Later you can use valuein your if statement like.
稍后你可以value在你的 if 语句中使用。
if(value > 0)
{
}
else
{
}
回答by laszlokiss88
Try with this:
试试这个:
int i = int.Parse(textbox1.Text);
回答by Karl
int value = 0;
if (Int32.TryParse(textbox.Text, out value))
{
if (value == 1)
{
... //Do something
}
else if (value == 2)
{
... //Do something else
}
else
{
... //Do something different again
}
}
else
{
... //Incorrect format...
}
回答by JohnnBlade
Try this
尝试这个
string value = myTextBox.Text;
int myNumber = 0;
if(!string.IsNullOrEmpty(value))
{
int.TryParse(value, out myNumber);
if(myNumber > 0)
{
// do stuff
}
}
回答by sam1589914
I would use:
我会用:
try
{
int myNumber = Int32.Parse(myTextBox.Text);
}
catch (FormatException ex)
{
//failed, not a valid number in string
throw;
}
or
或者
int myNumber = 0;
if (Int32.TryParse(myTextBox.Text, out myNumber))
{
//success do something with myNumber
}

