遍历_递归的妙用—遍历子控件

我们在asp.NET编程[bian cheng]中, 经常需要遍历[bian li]一个Web控件的子控件 ,找到所需的控件并获取控件中相应的值。以前我都是采用循环[xun huan]的方式遍历[bian li]子控件,但当子控件是复杂的树形结构[jie gou],比如:子控件也有子控件,子控件的子控件也有子控件。这时如果用循环[xun huan]的方式,就要用嵌套[qian tao]循环[xun huan][qian tao xun huan],而有时我们很难确定我们所要找的控件在子控件树的哪一层,昨天我就为些付出了代价,因为一个控件在内部增加了Panel控件,并将它的子控件移到了Panel控件上,我通过循环[xun huan]怎么也找不到所需的控件。
     既然子控件表现为一个树形结构[jie gou],为什么我不用递归去遍历[bian li]子控件?当我看着不太优雅的嵌套[qian tao]循环[xun huan][qian tao xun huan]代码[dai ma]时,我突然这样想到。使用递归,根本不用关心所需的控件在哪一层,而且代码[dai ma]简洁。
     下面就是两种遍历[bian li]方式:
1、循环[xun huan]方式:
for (int i =0; i<GlobalCategoryPanel.Controls.Count;i++)//GlobalCategoryPanel是个Panel控件
            {
                if(GlobalCategoryPanel.Controls[i] is AdvancedPanel)//AdvancedPanel是个自定义控件[zi ding yi kong jian]
                {
                    AdvancedPanel ap=(AdvancedPanel)GlobalCategoryPanel.Controls[i];
                    for(int ap_i=0;ap_i<ap.Controls.Count;ap_i++)
                    {
                        if(ap.Controls[ap_i] is Panel)
                        {
                            Panel ap_panel=(Panel)ap.Controls[ap_i];
                            for(int ap_panel_i=0;ap_panel_i<ap_panel.Controls.Count;ap_panel_i++)
                            {
                                if(ap_panel.Controls[ap_panel_i] is RadioButtonList)
                                {
                                    RadioButtonList rbl=(RadioButtonList)ap_panel.Controls[ap_panel_i];
                                    al.Add(int.Parse(rbl.SelectedValue));
                                }
                                               
                            }
                        }
                    }
                }
            }
2、递归方式
private void Button1_Click(object sender, System.EventArgs e)
        {
            FindSelecedControl(GlobalCategoryPanel);
        }
        private void FindSelecedControl(Control control)//递归函数[han shu][di gui han shu]
        {
            if(control is RadioButtonList)
            {
                RadioButtonList rbl=(RadioButtonList)control;
                al.Add(int.Parse(rbl.SelectedValue));
            }
            else
            {
                for(int i=0;i<control.Controls.Count;i++)
                {
                    FindSelecedControl(control.Controls[i]);
                }
            }
        }

原文地址:https://www.cnblogs.com/xiaofengfeng/p/1822217.html