WinForms按钮数组 [英] WinForms Button Array

查看:65
本文介绍了WinForms按钮数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C#,并且已经练习了如何使用Windows Forms创建计算器。现在,我只添加了9个数字按钮和4个用于随意操作(+,-,*,/)的按钮,以及一个将数字写为字符串的标签。目前我正在这样做:

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

记住DRY原理,这对我来说似乎是不好的编写代码。
有没有办法写得更好?我想到了类似按钮数组/列表的东西。所以我可以做这样的事情:

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

现在的问题是,我想在Windows中编辑按钮属性-forms-Designer-View。
我可以得到由这样的自写代码创建的按钮的设计视图吗?

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

或者是否可以从Form1中自动创建按钮数组?
我尝试了此操作(没有用):

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


推荐答案

如果按钮名称遵循某种模式(例如,单词按钮加数字),您可以使用循环从控件形式的集合中按名称收集它们:

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

这篇关于WinForms按钮数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆