苏飞论坛

标题: 一道面试题:如何遍历窗体所有Button? [打印本页]

作者: zzahkj    时间: 2013-5-23 14:10
标题: 一道面试题:如何遍历窗体所有Button?
是如下这样写吧
[code=csharp]foreach (Control c in this.Controls)
            {
                Control c1 = c as Button;
                if (c1 != null)
                {
                    //c1
                }
            }[/code]
作者: 中国人    时间: 2013-5-23 14:23
可以
作者: 站长苏飞    时间: 2013-5-23 14:31
还可以这样写,
你的方法有点另类了
[code=csharp] foreach (Control c in this.Controls)
            {
                if (c.GetType().Name == "Button")
                {
                    //Button个数统计
                }
                if (c.GetType().Name == "Textbox")
                {
                    //Textbox个数统计
                }
            }[/code]
作者: zzahkj    时间: 2013-5-23 14:39
站长苏飞 发表于 2013-5-23 14:31
还可以这样写,
你的方法有点另类了

哈哈 谢谢指教

作者: 边境之南    时间: 2014-10-11 10:27
站长苏飞 发表于 2013-5-23 14:31
还可以这样写,
你的方法有点另类了

决定把俺的第一次评论献给站长苏飞,我觉得,你们的方法容器内的Button遍历不到,不如写递归遍历它们。
[C#] 纯文本查看 复制代码
        private void SearchButton(Control c)
        {
            foreach (Control item in c.Controls)
            {
                if (item is Button)
                {
                   //To do something
                }
                else
                {
                    SearchButton(item);
                }
            }
        }

顺便提个建议,编辑代码不大方便,框框太小,不能缩放。
作者: 坏小孩    时间: 2014-11-22 23:46
我只是路过打酱油的。




欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4