获取表单的所有文本框,其名称按升序排列

Sdp*_*Sdp 1 c# sorting visual-studio-2013

我在一个表单中共有36个文本框,文本框的名称为txtBox1,txtBox2 ..... to txtBox36.其中一些textBox填写在form_load事件上.

我希望得到所有文本的盒子名称,它们是按升序排列的.

我尝试过的:

foreach (Control control in this.Controls)
{
    if (control is TextBox)
    {
        if (String.IsNullOrEmpty(control.Text))
        {
            for (int j = 1; j <= 36; j++)
            {
                MessageBox.Show(control.Name.ToString());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它给出的是随机顺序

txtBox26
txtBox28
txtBox31
txtBox34
txtBox33
txtBox30
txtBox27
txtBox29
txtBox25
txtBox14
txtBox16
txtBox19
txtBox21
txtBox18
txtBox17
txtBox23
txtBox24
txtBox13
txtBox7
txtBox10
txtBox6
txtBox3
txtBox11
txtBox12
Run Code Online (Sandbox Code Playgroud)

Rom*_*och 5

您可以使用LINQ以获取所有按名称排序的文本框:

var allTexboxes = this.Controls.OfType<TextBox>();
var sortedTextBoxes = allTexboxes
                     .Where(i => String.IsNullOrEmpty(i.Text))
                     .OrderBy(i => i.Name)
                     .ToArray();
Run Code Online (Sandbox Code Playgroud)

然后你可以这样得到名字:

var name = sortedTextBoxes[0].Name;
Run Code Online (Sandbox Code Playgroud)

如果您只想将名称作为字符串数组:

var allTexboxes = this.Controls.OfType<TextBox>();
var sortedNames = allTexboxes
                 .Where(i => String.IsNullOrEmpty(i.Text))
                 .OrderBy(i => i.Name)
                 .Select(i => i.Name)
                 .ToArray();
Run Code Online (Sandbox Code Playgroud)

得到名字:

var name = sortedNames[0];
Run Code Online (Sandbox Code Playgroud)