3

I am new to C# and I am following this C# tutorial at the moment. In this tutorial I came across the exercise to develop a calculator.

A C# .Net Calculator - Design Stage

In the solution given in the exercise, each digit button was given a btn*_click method which can be generalized pretty easily.

1
(source: homeandlearn.co.uk)

How can we write the code, so that we can generalize these 10 functions? I though it can be done by modifying initializeComponent(), but comment about it says it should not be modified using code editor.

How can this problem be tackled?

3
  • In the future you should copy-paste the code rather than using an image. If you indent 4 spaces (or a tab) in front of all the code (or click the {} button in the editor, which does the same thing), it will automatically format. Commented Jun 21, 2012 at 17:34
  • @mellamokb - it is an image linked from the site, which has a gif of the code. Commented Jun 21, 2012 at 17:36
  • @afuzzyllama: Ah, k, that makes sense :) Commented Jun 21, 2012 at 17:37

3 Answers 3

9

You can tie all buttons to the same click event handler, and use sender to get the text:

private void btnAnyButton_Click(object sender, EventArgs e)
{
    Button theButton = sender as Button;
    txtDisplay.Text += theButton.Text;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Nathan has also posted a good visual on how to link all the buttons to the same event handler, which you may find helpful.
Answers given by you and @nathan explains it to me. Thanks a lot!
6

The tutorial you posted is using the visual editor in visual studios. By default the designer will generate code with the convention {controlname}_{eventname} you can explicitly assign a different event name in the properties window, and all the buttons could share the same event method.

enter image description here

And then it looks like you could refactor this like:

private void btn_click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    if(btn != null)
       txtDisplay.Text += btn.Text;
}

I hope that helps.

Comments

1

You could generate these buttons dynamically from the code and assign them some value in the tag attribute. From there, you can hook them all up to the same event handler (we're talking about the number buttons, as in 0,1,2,3,4...). In the onClick event handler you would get the tag value of the caller and do what you have to do.

Pseudocode:

void onClick(Button caller){
  int btnNb = (int) caller.Tag;
  //do what you have to do
}

The tag attribute is not necessary but I find it cleaner than getting the button text and converting to an int.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.