Get integer from Textbox(从文本框中获取整数)
问题描述
我对 C# 很陌生,这个问题听起来可能很愚蠢.我想知道如何从 textBox1
获取整数(用户输入)并在 if else 语句中使用它?
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 textBox1
and use it in if else statement?
请举几个例子
推荐答案
您需要将 textbox.Text
的值解析为 int
值的字符串.您可以使用 int.TryParse 或 int.Parse
或 Convert.ToInt32
.
You need to parse the value of textbox.Text
which is a string to int
value. You may use int.TryParse, or int.Parse
or Convert.ToInt32
.
TextBox.Text
属性是 string
类型.你可以看看下面的示例代码.
TextBox.Text
property is of string
type. You may look at the following sample code.
int.TryParse
如果解析成功,这将返回 true,如果解析失败,则返回 false.
This will return true if the parsing is successful and false if it fails.
int value;
if(int.TryParse(textBox1.Text,out value))
{
//parsing successful
}
else
{
//parsing failed.
}
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);
稍后您可以在 if 语句中使用 value
之类的.
Later you can use value
in your if statement like.
if(value > 0)
{
}
else
{
}
这篇关于从文本框中获取整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从文本框中获取整数


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01