• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
人生之路,职业之路
读书使人充实,交谈使人机敏,写记使人精确;
“动因+兴趣”——决心-持之以恒-见效
博客园    首页    新随笔    联系   管理    订阅  订阅
在asp.net和C#中如何根据字符串找到相应的控件?
以下两种方式全都是从网上找来的解决办法:

在Asp.net中可以使用反射实现,以TextBox为例  
   
  private   void   Page_Load(object   sender,   System.EventArgs   e)  
  {  
  //   在此处放置用户代码以初始化页面  
  TextBox   tb   =   new   TextBox();  
  this.Panel1.Controls.Add(tb);  
  if(!Page.IsPostBack)  
  {  
                            tb.ID="clt";  
                            tb.Text="TextBox的文本";  
  }  
   
   
  Response.Write   (this.GetPropertyValue("clt","Text"));  
   
  }  
   
  protected   string   GetPropertyValue(string   ControlID,string   PropertyName)  
  {  
  Control   c=null;  
  this.FinControlFromID(this,ControlID,ref   c);  
  if(c==null)  
                            return   string.Empty;  
   
  System.Type   t=c.GetType();  
  return   t.InvokeMember(PropertyName,System.Reflection.BindingFlags.GetProperty,null,c,null).ToString();  
  }  
   
  //遍历查找控件  
  protected   void   FinControlFromID(Control   ParentControl,string   ControlID,ref   Control   ctr)  
  {  
  foreach(Control   c   in   ParentControl.Controls)  
  {  
                          if(c.ID==ControlID)  
                          {  
              ctr=c;break;  
                          }  
                          FinControlFromID(c,ControlID,ref   ctr);  
  }  
   
  }

在C#中, 则直接使用以下方式:
string   str   =   "abc ";
((Button)(this.Controls.Find(str,   true)[0])).PerformClick();
posted on 2009-07-31 10:10  FreeBird  阅读(536)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3