使用 C# 获取表单中的所有文本框名称时使用什么函数?

问题描述:

我想知道如何使用 C# 获取表单中的所有文本框名称?

I want to know how can I get all the textbox names in a form using C#?

这是我生成动态文本框的代码:

Here is my code in generating dynamically textboxes:

private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 1; i <= 5; i++)
        {
            TextBox txtbox = new TextBox();
            txtbox.Name = "txtbox" + i;
            flowLayoutPanel1.Controls.Add(txtbox);

            Label lbl = new Label();
            lbl.Name = "lbl" + i;
            lbl.Text = lbl.Name;
            flowLayoutPanel2.Controls.Add(lbl);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string[] textBoxNamesArray = this.Controls.OfType<TextBox>()
                                      .Select(r => r.Name)
                                      .ToArray();

        var textboxes = string.Join(",", textBoxNamesArray);

        MessageBox.Show(textboxes);
    }

您可以使用 LINQ 从当前表单中获取 TextBox 类型的控件的所有名称.以下查询将返回一个包含所有名称的字符串数组.

You can use LINQ to get all the names of the controls of type TextBox from the current form. The following query will return you an array of strings containing all the names.

string[] textBoxNamesArray = flowLayoutPanel1.Controls.OfType<TextBox>()
                                          .Select(r => r.Name)
                                          .ToArray();

记得包含using System.Linq;