当您动态创建未知数量的按钮时如何引用每个按钮?

How to refer to each button when u dynamically create an uknown amount of them?

Char[] mychars = { ' ' };
            string myText = "Hello how are you";
            string[] names = myText.Split(mychars);
            int idef=0;
            foreach(string x in names)
            {
                Button b = new Button
                {
                    Width = 100,
                    Name = "b" + idef,
                    Text = x,
                    Location = new Point(centerLine.Location.X + idef * 100, centerLine.Location.Y),
                };
                b.Click += (sender1, e1) =>
                {
                    textBox1.Text += ((Button)sender1).Text;
                };
                this.Controls.Add(b);
                idef++;
            }

            b0.Text = "change";

b0 是我创建的一个按钮,但它在当前上下文中不存在,我该如何引用它本身?我在 visual studio 它的 Forms 应用程序中工作。

this.Controls.Add(b);

如果要将按钮添加到 this.Controls,您应该能够使用 LINQ 访问所有这些按钮。要添加其功能,请使用:

using System.Linq;

然后,可以得到控件中的所有按钮:

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

或所有名称以字母'b'开头的按钮:

var buttons = this.Controls.OfType<Button>().Where(x => x.Name.StartsWith("b"));

之后,您可以使用 LINQ 在按钮列表中搜索:

var b0 = buttons.Where(x => x.Name == "b0").SingleOrDefault();

或者在 this 中搜索整个 ControlCollection,而不创建 'buttons' 变量。使用 SingleOrDefault() 方法 return 一个具有特定名称的按钮:

var b0 = this.Controls.OfType<Button>().Where(x => x.Name == "b0").SingleOrDefault();

当您想要更改按钮的文本或任何其他内容时 属性,只需使用:

b0.Text = "New Text";

要了解有关 LINQ 的更多信息,请访问 this page. All the LINQ methods are available here

如果您不想使用 LINQ 检索按钮,您可以简单地 select 使用 foreach 循环和 is 关键字检查类型的所有按钮:

var buttons = new List<Button>();

foreach (var control in this.Controls)
{
     if (control is Button button)
     {
          buttons.Add(button);
     }
}

或select所有名称以字母'b':

开头的按钮
var buttons = new List<Button>();

foreach (var control in this.Controls)
{
     if (control is Button button && button.Name.StartsWith("b"))
     {
          buttons.Add(button);
     }
}

您还可以通过这种方式select 具有特定名称的按钮:

Button b0 = null;

foreach (var control in this.Controls)
{
     if (control is Button button && button.Name == "b0")
     {
          b0 = button;
          break;  // break keyword to stop the loop if the button is found
     }
}

然后,您可以编辑按钮的属性 'b0',但您必须确保按钮不为空:

if (b0 is not null)  // checks if button exists
{
     b0.Text = "New Text";
}