设置页面中的所有控件的某属性的方法

来源:未知 责任编辑:责任编辑 发表时间:2013-12-22 14:56 点击:

对于设置页面中所有控件的属性,需要使用递归的方法进行查找,并且可以使用反射去判断属性和设置属性值。代码如下:

ASPX 代码
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Reflection" %>
<%@ Import Namespace="System.ComponentModel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script runat="server">
  protected void Button1_Click(object sender, EventArgs e)
  {
    SetControlArrtibute(Page);
  }

  private void SetControlArrtibute(Control ctl)
  {
    Type type = ctl.GetType();
    PropertyInfo[] properties = type.GetProperties();
    Response.Write("<hr>");
    Response.Write(type.ToString());
    Response.Write("<br>");
    foreach (PropertyInfo property in properties)
    {
      // 不是所有的属性都能通过这种方法进行得到?
      if (property.Name == "Text" && property.PropertyType == typeof(String))
      {
        Response.Write("<li>" + property.Name + " = " + GetPropertyValue(ctl, property.Name));
      }
      if (property.Name.Equals("Enabled"))
      {
        Type propertyType = property.PropertyType;
        TypeConverter converter = TypeDescriptor.GetConverter(propertyType);
        Object arg = converter.ConvertFrom("false");
        object[] args = { arg };
        BindingFlags flags = BindingFlags.SetProperty;
        Binder binder = null;
        type.InvokeMember("Enabled", flags, binder, ctl, args);
      }
    }

    if (ctl.HasControls())
    {
      foreach (Control c in ctl.Controls)
      {
        SetControlArrtibute(c);
      }
    }
  }

  private String GetPropertyValue(Control control, String propertyName)
  {
    Type type = control.GetType();
    BindingFlags flags = BindingFlags.GetProperty;

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • 浅析.NET下XML数据访问新机制
  • asp.net 面试+笔试题目第1/2页
  • C# 邮件地址是否合法的验证
  • asp.net 设置GridView的选中行的实现代码
  • C#高级编程:数据库连接[1]
  • 经典C++程序1
  • IIS 自动回收导致后台定时器失效的问题解决
  • ASP.NET&#160;GridView列表代码示例
  • Asp.net MVC源码分析--Action Filter的链式调用
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1