C# 遍历窗体控件顺序问题

今天在做C# winform 窗体控件遍历时遇到控件顺序的问题,也就是控件被遍历的先后问题。实际情况如下所述。

窗体界面如下:

C# 遍历窗体控件顺序问题

界面构成是:主界面有一个 Panel (Panel_14),Panel_14上面有13个子 Panel(Panel_1 ~ Panel_13),每个子 Panel 上有10个 TextBox,为了便于操作TextBox中的数据需要将每个子Panel中的TextBox按照顺序存储到一个TextBox二维数组中 TextBoxArray[10, 13],实现代码如下:

foreach(System.Windows.Forms.Control control in this.panel14.Controls)
{
    if (control is System.Windows.Forms.Panel)
    {
        System.Windows.Forms.Panel p = (System.Windows.Forms.Panel)control;
        int i = int.Parse(p.Name.Substring(5)) - 1;
        int j = 0;
        foreach (System.Windows.Forms.Control cn in p.Controls)
        {
            if (cn is System.Windows.Forms.TextBox)
            {
                textBoxArray[i,j++] = (System.Windows.Forms.TextBox)cn;
            }
        }
    }
}

但是在实际调试时发现TextBox并没有哦按照预想的那样从上到下,从左至右一次存入TextBoxArray中,如下图所示:

C# 遍历窗体控件顺序问题

红色方框的地方,Text = “29” 是Panel_2 的最后一个TextBox,但是在遍历的时候却是第一个,而且13个Panel也不是从Panel_1 到 Panel_13一次遍历的,而是第一个遍历Panel_1,第二个遍历Panel_13,第三个遍历Panel_2........,对于强迫症的我来说这是不允许的,而且这也给TextBox的数据操作带来不便,解决这种问题的方法也有很多种,例如:

1. 可以和操作 textBoxArray 的第一个纬度一样通过控件的 name 来实现,textBoxArray[int.parse(p.name.subString(5)) - 1, int.parse(textBox.name.subString(6)) - 1] = textBox;

2. 通过TextBox的 TabIndex 或者 Tag 实现,代码同1;

3. 通过修改通过修改 ...Controls.Add(...);的顺序来实现,因为控件在界面中是通过 ......Controls.Add(...);添加的,控件遍历的顺序和控件添加的顺序是一致的,先添加的先遍历,如下图:

C# 遍历窗体控件顺序问题

红色方框是Panel_14中子Panel添加的顺序,所有就有了上面说的先遍历Panel_1,然后遍历Panel_13,然后遍历Panel_2...................

至此,问题得到解决。