WinForms Button Array

久未见 提交于 2019-12-13 06:18:10

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/42365228/winforms-button-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!