在我的程序中,我有几个文本框和按钮,它们具有相应的名称(例如 TextBox1 - buttonPlus1),如图所示
但其中充满了从文本文件加载的数字。 我想编写允许我按下按钮 + 并从文本框中放大(添加固定数字,例如 100)值的函数。到目前为止我已经完成了:
private void buttonPlus1_Click(object sender, EventArgs e)
{
AddValue(sender,e);
}
private void AddValue(object sender, EventArgs e)
{
if (!(sender is Button))
return;
string controlName = (sender as Button).Name;
string textBoxName = controlName.Replace("buttonPlus", "textBox");
TextBox textBox = this.Controls.Find(textBoxName, false)[0] as TextBox;
int step = 100;
}
但我不知道如何从 textBox 中获取值(作为数字)并添加该步骤。有人能帮帮我吗?我尝试了很多不同的方法自己解决它,但它不起作用
最佳答案
获取值:
Convert.ToInt32(textBox.Text)
将它保存到一个变量中,加上 100 并像往常一样设置它。
附言您还可以使用 Int32.Parse("")
textBox.Text = Convert.ToInt32(textBox.Text) + 100;
(您可能需要 .ToString()
它)
编辑: 正如 ltiong_sh 提到的,您应该使用 TryParse 而不是 Parse:
int somevalue;
if(Int32.TryParse(textBox.Text, out somevalue))
{
textBox.Text = somevalue + 100;
}
关于c# winForm 向文本框中的数字添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10843303/