c#更改for循环中控件的名称

时间:2016-01-08 01:18:05

标签: c# winforms

我正在创建一个程序,它将在for循环中在屏幕上创建按钮。这很重要,因为用户需要访问多个按钮,并且每次运行都可能会发生变化。这是我到目前为止的代码:

public Form1()
    {
        InitializeComponent();
        int top = 5;
        int left = 5;
        for (int i = 0; i < 10; i++)
        {
            Button button = new Button();
            button.Height = 50;
            button.Left = left;
            button.Top = top;
            this.Controls.Add(button);
            left += button.Width + 2;
        }
    }

我想要的基本上是这样的:

Button b+i = new Button();

就像组合两个字符串一样,我希望循环中第一次运行时按钮的名称为b0,然后是b1,然后是b2,依此类推。

我使用Visual Studio,并且InitializeComponent()转到编辑器生成的代码来制作窗口和东西。只有窗户在那里制作。

感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

担心变量名称是解决此问题的错误方式。有几种选择:

使用列表

List<Button> buttons;    

public Form1()
{
    InitializeComponent();
    buttons = new List<Button>();
    int top = 5;
    int left = 5;
    for (int i = 0; i < 10; i++)
    {
        Button button = new Button();
        button.Height = 50;
        button.Left = left;
        button.Top = top;
        this.Controls.Add(button);
        buttons.Add(button);
        left += button.Width + 2;
    }
}
//now instead of 'b1', it's 'buttons[1]'

您也可以使用OfType()方法创建:

var buttons = this.Controls.OfType<Button>().ToList();

这些可以与FlowLayoutPanel或TableLayoutPanel结合使用以简化代码:

public Form1()
{
    InitializeComponent();

    for (int i = 0; i < 10; i++)
    {
        Button button = new Button();
        button.Height = 50;
        FlowLayoutPanel1.Controls.Add(button); //panel handles Left/Top location
    }
}

该面板还具有帮助您的应用扩展到不同dpi或屏幕/窗口大小的优势。

其中任何一个也可以适应于开始考虑连接数据源(并减少代码):

var buttons = Enumerable.Range(0, 10).Select(b => new Button {
   Height = 50,
   Left = 5 + ( b * (BUTTONWIDTH + 2) ),
   Top = 5,
   Name = String.Format("Button{0}", b)
});

//buttons.ToList()
//or
//this.Controls.AddRange(buttons.ToArray())
//or 
//FlowLayoutPanel1.Controls.AddRange(buttons.ToArray()) //Remove Left/Top code

但是所有这些都没有意义,直到你可以让按钮实际上做某事。您需要(至少)Click事件的事件处理程序:

foreach (var b in butons)
{
     b.Click += (s,e) => 
    { 
        //click code for all of the buttons goes here
        // you can tell the buttons apart by looking at the "s" variable 

    };
}

答案 1 :(得分:1)

因为人们(正确地)说“使用数组”这里是代码

public Form1()
    {
        InitializeComponent();
        int top = 5;
        int left = 5;
        var buttons = new Button[10];
        for (int i = 0; i < 10; i++)
        {
            Button button = new Button();
            button.Height = 50;
            button.Left = left;
            button.Top = top;
            this.Controls.Add(button);
            left += button.Width + 2;
            buttons[i] = button;
        }
    }