tags:

views:

143

answers:

1

I've written a simple calculator program using C# and WinForms. But it doesn't really do anything useful. How should I be handling the calculator buttons?

My code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace lab8ass1
{
    public partial class Form1 : Form
    {

    public Form1()
    {
        InitializeComponent();
    }

    private void button11_Click(object sender, EventArgs e)
    {
        textBox1.Text += ".";
    }

    private void btnone_Click(object sender, EventArgs e)
    {
        textBox1.Text += "1";
    }

    private void btnrwo_Click(object sender, EventArgs e)
    {
        textBox1.Text += "2";
    }

    private void btnthree_Click(object sender, EventArgs e)
    {
        textBox1.Text += "3";
    }

    private void btnfour_Click(object sender, EventArgs e)
    {
        textBox1.Text += "4";
    }

    private void btnfive_Click(object sender, EventArgs e)
    {
        textBox1.Text += "5";
    }

    private void btnsix_Click(object sender, EventArgs e)
    {
        textBox1.Text += "6";
    }

    private void btnseven_Click(object sender, EventArgs e)
    {
        textBox1.Text += "7";
    }

    private void btneight_Click(object sender, EventArgs e)
    {
        textBox1.Text += "8";
    }

    private void btnnine_Click(object sender, EventArgs e)
    {
        textBox1.Text += "9";
    }

    private void btnzero_Click(object sender, EventArgs e)
    {
        textBox1.Text += "0";
    }
    string s1,s;
    private void btnplus_Click(object sender, EventArgs e)
    {
        s1 = textBox1.Text;
        textBox1.Text = "";
        s = textBox1.Text;

        //textBox1.Text
    }


    private void btnequal_Click(object sender, EventArgs e)
    {

    }


  }

}
+5  A: 

You can use:

private void allButtons_Click(object sender, EventArgs e)
{
    Button b = sender as Button;
    textBox1.Text += b.Text;
}

And use this handler for all your buttons (whose Text you want appended to textBox1)

Henk Holterman
or as a one-liner: `textBox1.Text += ((Button)sender).Text;`
dboarman
@dboarman: I don't think the one-liner is any better or clearer. I prefer simpler steps.
Henk Holterman
@Henk: I suppose for someone new, it wouldn't be any clearer. I added that comment in there as an option - it's the way I do it, one less declaration that isn't really needed on something this simple. If I had multiple operations to perform with sender, then I would instance a reference as you did above.
dboarman
@dboarman: I still tend to fold them too, until I stop myself. Its very easy to overdo.
Henk Holterman