繁体   English   中英

如何在 C# 中不使用单击事件(按钮)来计算总数?

[英]How to calculate a total without using a click event (button) in C#?

我正在使用 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();
       }

我想要做的是改变 textBox3 中的结果,因为我从组合框中选择运算符而无需按下按钮。 我试过使用 Leave 事件但没有成功。 任何帮助将不胜感激。

您可以连接到 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();
}

以上是伪代码,但只需添加“textChanged”事件并将代码放入其中,如上所示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM