[英]How to calculate a total without using a click event (button) in C#?
I'm doing a simple calculator using C# and I already made it work when I press a button, like this.我正在使用 C# 做一个简单的计算器,当我按下一个按钮时,我已经让它工作了,就像这样。
private void button1_Click(object sender, EventArgs e)
{
int a = int.Parse(textBox1.Text);
int b = int.Parse(textBox2.Text);
if (comboBox1.Text == "+")
textBox3.Text = (a + b).ToString();
if (comboBox1.Text == "-")
textBox3.Text = (a - b).ToString();
if (comboBox1.Text == "*")
textBox3.Text = (a * b).ToString();
if (comboBox1.Text == "/")
textBox3.Text = (a / b).ToString();
}
What I'm trying to do is for the result in textBox3 to change as I choose the operator from the comboBox without having to press a button.我想要做的是改变 textBox3 中的结果,因为我从组合框中选择运算符而无需按下按钮。 I've tried using the Leave event with no success.我试过使用 Leave 事件但没有成功。 Any help will be appreciated.任何帮助将不胜感激。
您可以连接到 SelectedIndexChange 事件
private void combobox1_textChanged(object sender, EventArgs e)
{
int a = int.Parse(textBox1.Text);
int b = int.Parse(textBox2.Text);
if (comboBox1.Text == "+")
textBox3.Text = (a + b).ToString();
if (comboBox1.Text == "-")
textBox3.Text = (a - b).ToString();
if (comboBox1.Text == "*")
textBox3.Text = (a * b).ToString();
if (comboBox1.Text == "/")
textBox3.Text = (a / b).ToString();
}
The above is pseduo code, but just add the "textChanged" event and put the code inside like shown above.以上是伪代码,但只需添加“textChanged”事件并将代码放入其中,如上所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.