c#中的textbox输入数值如何运算?

2025-03-20 10:15:30
推荐回答(2个)
回答1:

键入textbox内的数字,并不是以Int类型来存储,而是看作字符串,被存放在TextBox.Text属性中。
要将它转换为Int类型,可以使用Int32.Parse 方法
它负责将数字的字符串表示形式转换为它的等效 32 位有符号整数。

下面的示例演示如何使用 Int32.Parse(String) 方法将字符串值转换为 32 位有符号整数值。 然后,将生成的整数值显示到控制台。
using System;
public class ParseInt32
{
public static void Main()
{
Convert(" 179 ");
Convert(" -204 ");
Convert(" +809 ");
Convert(" 178.3");
}
private static void Convert(string value)
{
try { int number = Int32.Parse(value);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
} catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", value);
}
}
}
// This example displays the following output to the console:
// Converted ' 179 ' to 179.
// Converted ' -204 ' to -204.
// Converted ' +809 ' to 809.
// Unable to convert ' 178.3'.

回答2:

int num1=parse.Int32(texBox1的name.Text);//将第一个文本框的内容转换为整型
int num2=parse.Int32(texBox2的name.Text);//将第二个文本框的内容转换为整型
int result=num1+num2;//将两文本框内容想加
textBox3.Text=result.ToString();//将结果赋值文本框3