如何在C#中将文本框转换为int

How to convert textbox to int in c#

我输入了 textbox=1,我想像这样添加一个:

Textbox.text+=1;

但不添加它 apear (11) 我想 apear (2)

您需要将其转换为 int 然后添加 1

int temp_ans = Convert.ToInt32(Textbox.text) + 1;
Textbox.text = temp_ans.ToString();
int answer = Convert.ToInt32(Textbox.text);
 answer =+1;

我想稍微扩展一下 Darth-CodeX 答案。

您的文本框是字符串(文本)类型。您尝试执行的操作(加 +1)仅适用于数字类型。
在文本上使用 += 时,它会尝试将输入自动转换为文本 1 (number) -> "1" (text)。 您展示的示例是将字母添加(附加)到现有字符串(文本) 示例:

Textbox.Text += "Apples";
Textbox.Text += " are ";
Textbox.Text += " awesome!";

为了以数学方式处理数字,您需要先将文本转换为数字:

int conversion = int.Parse(Textbox.Text); // convert to int (1,2,3,4,...)
// double conversionWihDecimal places; // convert to double (1.213221)
conversion += 1; // add 1 to conversion
Textbox.Text = conversion.ToString(); // convert back and update textbox

请注意,如果您尝试将文本“Apple”解析为数字,您的应用程序将会崩溃。您可以添加检查功能或使用 int.TryParse()。我在下面的示例中使用双精度,因为它也将包含小数位 (123.321)。此外,我使用 .Trim() 删除文本开头和结尾的所有空格。

double conversion;
if (double.TryParse(Textbox.Text.Trim(), out conversion)
{
    conversion += 1; // add 1 to conversion
    Textbox.Text = conversion.ToString(); // convert back and update textbox
}