📄 calculator.cs
字号:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace snowy
{
public class Calculator : Control , INamingContainer
{
private TextBox txtDisplay;
public int Result
{
get
{
if( ViewState["Result"] == null )
{
ViewState["Result"] = 0;
return 0;
}
else
return (int)ViewState["Result"];
}
set
{
ViewState["Result"] = value;
}
}
private string Status
{
get
{
if( ViewState["Status"] == null )
{
ViewState["Status"] = "number1input";
return "number1input";
}
else
return (string)ViewState["Status"];
}
set
{
ViewState["Status"] = value;
}
}
private void HandleDigit(string digit)
{
txtDisplay.Text += digit;
if( Status == "number1input" )
{
Result = int.Parse(txtDisplay.Text);
}
}
protected override bool OnBubbleEvent(object sender, EventArgs e)
{
if(sender is Button)
{
string text = ((Button)sender).Text.Trim();
switch(text)
{
case "+":
if(Status == "number1input")
{
Status = "number2input";
txtDisplay.Text = "";
}
else
{
Result = Result + int.Parse(txtDisplay.Text);
txtDisplay.Text = "";
}
break;
case "=":
if( Status == "number2input" )
{
Status = "number1input";
txtDisplay.Text = (Result + int.Parse(txtDisplay.Text)).ToString();
Result = int.Parse(txtDisplay.Text);
}
break;
default:
HandleDigit(text);
break;
}
}
return true;
}
private TableCell CreateButtonCell(string text)
{
TableCell cell = new TableCell();
Button button = new Button();
button.Text = text;
cell.Controls.Add(button);
return cell;
}
protected override void CreateChildControls()
{
txtDisplay = new TextBox();
txtDisplay.ReadOnly = true;
Controls.Add(txtDisplay);
Controls.Add(new LiteralControl("<br/>"));
Table table = new Table();
TableRow row;
row = new TableRow();
row.Cells.Add(CreateButtonCell(" 1 "));
row.Cells.Add(CreateButtonCell(" 2 "));
row.Cells.Add(CreateButtonCell(" 3 "));
row.Cells.Add(CreateButtonCell(" 4 "));
table.Rows.Add(row);
row = new TableRow();
row.Cells.Add(CreateButtonCell(" 5 "));
row.Cells.Add(CreateButtonCell(" 6 "));
row.Cells.Add(CreateButtonCell(" 7 "));
row.Cells.Add(CreateButtonCell(" 8 "));
table.Rows.Add(row);
row = new TableRow();
row.Cells.Add(CreateButtonCell(" 9 "));
row.Cells.Add(CreateButtonCell(" 0 "));
row.Cells.Add(CreateButtonCell(" + "));
row.Cells.Add(CreateButtonCell(" = "));
table.Rows.Add(row);
Controls.Add(table);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -