我正在尝试使用C#创建一个带有Windows窗体的基本数学机器。
所以我设置了2个文本框,1个标签和一个按钮。用户将两个值放在文本框中,然后按下按钮以获得标签中两个文本框的总和。
我是Windows Forms的新手,不知道如何获取文本框的值,然后更改标签。
谢谢。
答案 0 :(得分:0)
这是一个非常简单的要求。
假设整数值输入文本框。
private void button1_Click(object sender, EventArgs e)
{
// Declare variables for addition
int a, b;
// If convertion of textbox values to integer is successful
// If integer parsing is successful, the value entered in textbox1 will go to variable a
// and the value entered in textboxb will go to variable b
if (int.TryParse(textBox1.Text, out a) && int.TryParse(textBox2.Text, out b))
{
// Add a and b and assign display its value in label
label1.Text = (a + b).ToString();
}
}
希望这会有所帮助。作为新浪的评论。我还建议你通过一个基本的端到端C#教程,它会给你一个快速的开始。
答案 1 :(得分:0)
由于您正在执行数学运算,因此最好在文本框中实现整数验证。这通常可以通过TextChange事件来完成。
至于你的问题,你可以简单地创建一个类似于下面的简单道具来获取文本框值:
public int Value1
{
get
{
int value = 0;
int.TryParse(textBox1.Text.Trim(), out value);
return value;
}
}
答案 2 :(得分:0)
试试这个,@ John Iacino
private void button1_Click(object sender, EventArgs e)
{
int firstnum;
int secondnum;
int ans;
firstnum=int.parse(textbox1.text);
secondnum=int.parse(textbox2.text);
ans=firstnum+secondnum;
label1.text=ans.Tostring();
}
答案 3 :(得分:0)
你可以写一个类似的方法/类;
public string Add(string v1,string v2)
{
int i1 = Convert.ToInt32(v1);
int i2 = Convert.ToInt32(v2);
return (i1 + i2).ToString();
}
label1.text=Add(textBox1.Text,textBox2.Text); // write into button click event
答案 4 :(得分:0)
decimal v1 = 0;
decimal v2 = 0;
decimal v3 = 0;
if (decimal.TryParse(TxtBx1.Text, out v1) & decimal.TryParse(TxtBx2.Text, out v2) &
decimal.TryParse(Text3, out v3))
{
decimal total = v1+v2+v
TotalTxtBx.Text = total.ToString();
}