现在的位置: 首页 > 综合 > 正文

遍历和查找容器内的控件.

2012年09月07日 ⁄ 综合 ⁄ 共 3436字 ⁄ 字号 评论关闭
前台界面:

后台代码:

  1using System;
  2using System.Collections;
  3using System.ComponentModel;
  4using System.Data;
  5using System.Drawing;
  6using System.Web;
  7using System.Web.SessionState;
  8using System.Web.UI;
  9using System.Web.UI.WebControls;
 10using System.Web.UI.HtmlControls;
 11
 12namespace AspNetTest.Common
 13{
 14    /// <summary>
 15    /// MoreControls 的摘要说明。
 16    /// </summary>

 17    public class Controls : System.Web.UI.Page
 18    {
 19        protected System.Web.UI.WebControls.Panel Panel1;
 20        protected System.Web.UI.WebControls.Panel Panel2;
 21        protected System.Web.UI.WebControls.TextBox TextBox2;
 22        protected System.Web.UI.WebControls.Label Label1;
 23        protected System.Web.UI.WebControls.Button Button1;
 24        protected System.Web.UI.WebControls.Label Label2;
 25        protected System.Web.UI.WebControls.TextBox TextBox3;
 26        protected System.Web.UI.WebControls.Button Button2;
 27        protected System.Web.UI.WebControls.TextBox TextBox1;
 28    
 29        private bool bFound = false;
 30        private void Page_Load(object sender, System.EventArgs e)
 31        {
 32            // 在此处放置用户代码以初始化页面
 33        }

 34
 35        Web 窗体设计器生成的代码
 57
 58        private void Button1_Click(object sender, System.EventArgs e)
 59        {
 60            GetTextBoxValues(Panel1);
 61        }

 62        private void GetTextBoxValues(Control c)
 63        {
 64            if(c is TextBox)
 65            {
 66                Label1.Text += c.ID + " 的值:" + ((TextBox)c).Text + "<br>";
 67            }

 68            else
 69            {
 70                for(int i=0; i<c.Controls.Count; i++)
 71                {
 72                    GetTextBoxValues(c.Controls[i]);
 73                }

 74            }

 75        }

 76        private void SearchTextBoxValue(Control c, string SearchId)
 77        {
 78            if(c is TextBox)
 79            {
 80                if(c.ID == SearchId)
 81                {
 82                    Label1.Text = c.ID + " 的值:" + ((TextBox)c).Text + "<br>";
 83                    bFound = true;
 84                }

 85            }

 86            else
 87            {
 88                for(int i=0; i<c.Controls.Count; i++)
 89                {
 90                    SearchTextBoxValue(c.Controls[i], SearchId);
 91                }

 92            }

 93        }

 94
 95        private void Button2_Click(object sender, System.EventArgs e)
 96        {
 97            string SearchTextBoxId = TextBox3.Text.Trim();
 98            SearchTextBoxValue(Panel1, SearchTextBoxId);
 99            if(bFound == false)
100            {
101                Label1.Text = "<font color=red>没有找到ID值为 " + SearchTextBoxId + "的文本框</font>";
102            }

103        }

104    }

105}

106

效果图1:

效果图2:

抱歉!评论已关闭.