0

I'm learning C# and I've got the exercise to create a calculator with Windows Forms. Right now I just added 9 buttons for the numbers and 4 buttons for the casual operations (+,-,*,/) and a label to write in the numbers as strings. Currently I'm doing this:

private void button1_Click(object sender, EventArgs e)
{
    WriteInLabel(1);
}

private void button2_Click(object sender, EventArgs e)
{
    WriteInLabel(2);
}
//etc.

//function to write the Text in label1
private void WriteInLabel(int i)
{
    label1.Text += i.ToString();
}

And remembering the DRY principle, this looks like kind of bad written code to me. Is there a way to write this better? I thought of something like a button array/List. So I could do something like this:

for(int i = 0; i < btnArr.Length; i++)
{
    //Is this the correct syntax for appending an eventListener?
    btnArr[i]Click += (sender, args) => WriteInLabel(i);         
}

Now the problem is, I wanted to edit the button-properties in the Windows-forms-Designer-View. Can I get the Design-View of Buttons created by self-written code like this?

Button btn1 = new Button();

Or is it possible to automatically create an array of the buttons from the Form1? I tried this (didn't work):

List<Button> btnList = new List<Button>();
foreach(Button btn in Form1)
{
    btnList.Add(btn);   
}
2
  • In what way didnt it work? it would depend a little how the buttons were made, if they got added as children to the form etc? Commented Feb 21, 2017 at 10:50
  • Well, I just added them by dragging a Button-Form from the Toolbox to the Form1. And I get the red squiggly line under Form1 in my last code snippet, saying: Form1 is a type, which is not valid in the current context. Commented Feb 21, 2017 at 10:56

2 Answers 2

2

if button names follow some pattern (e.g. word "button" plus number), you can use a loop to collect them by names from Controls collection of the form:

List<Button> btnList = 
    Enumerable.Range(1,9)
    .Select(i => (Button)this.Controls["button"+i.ToString()])
    .ToList();

if number of buttons is small, it also makes sence to simply list them all in a collection initializer:

var btnList = new List<Button> { button1, button2, button3, ... button9};
Sign up to request clarification or add additional context in comments.

Comments

0

Not sure why you want to programmatically create an array of buttons: you can't get a design view of these buttons.

You could assign the same event handler in the designer to all your buttons and in the event handler do this:

 WriteInLabel((sender as Button).Text);

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.