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);
}