【发布时间】:2016-10-28 13:16:19
【问题描述】:
我正在制作一个基本计算器,它使用(发送者作为按钮)将相关按钮的文本属性发送到我用作显示的文本框,称为“calcScreen”。这意味着如果我按下文本值为“1”的按钮,它应该填充文本框。构建运行良好,但是当我按下数字按钮时,文本框保持空白。我是否错过了 Visual Studio 中的某个设置或代码错误?
using System;
using System.Windows.Forms;
namespace Calc
{
public partial class Form1 : Form
{
private double accumulator = 0;
private char lastOperaton;
public Form1()
{
InitializeComponent();
}
private void OperatorPressed(object sender, EventArgs e)
{
char operation = (sender as Button).Text[0];
if (operation == 'C')
{
accumulator = 0;
}
else
{
double currentValue = double.Parse(calcScreen.Text);
switch (lastOperaton)
{
case '+': accumulator += currentValue; break;
case '-': accumulator -= currentValue; break;
case '*': accumulator *= currentValue; break;
case '/': accumulator /= currentValue; break;
default: accumulator = currentValue; break;
}
}
lastOperaton = operation;
calcScreen.Text = operation == '=' ? accumulator.ToString() : "0";
}
private void NumberPressed(object sender, EventArgs e)
{
string number = (sender as Button).Text;
calcScreen.Text = calcScreen.Text == "0" ? number : calcScreen.Text + number;
}
}
}
【问题讨论】:
-
您是否真的将 NumberPressed 连接为按钮的事件处理程序,即如果您插入一个,调试器是否会在 NumberPressed 中遇到断点?
-
仍然不知道该怎么做。我还是个新手不好意思。例如,我会在 button1_click 中创建一个新的事件处理程序并将其链接到 NumberPressed 吗?我该怎么做?我以为 (sender as Button).Text 会收到按下的任何按钮的 text 属性?
-
如果您没有将 NumberPressed 方法连接为按钮的事件处理程序,则它永远不会被调用,因此您的 (sender as Button).Text 永远不会被执行。如果您甚至无法使用调试器检查该问题,那么您最好使用完整的教程,因为我们目前无法帮助您,除非您认为一些基本知识是理所当然的。如果您使用带有“tutorial visual studio 计算器”的搜索引擎,您会发现很多教程都可以通过它...
-
现在已排序,谢谢。为每个链接到 NumberPressed 的按钮添加了点击事件
标签: c#