当前位置:编程学习 > asp >>

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

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

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;
    Binder binder = null;
    object[] args = null;
    object result = type.InvokeMember(propertyName, flags, binder, control, args);
    return Convert.ToString(result);
  }

  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {
      GridView1.DataSource = new String[] { "A", "B" };
      GridView1.DataBind();
    }
  }
</script>
<head id="Head1" runat="server">
  <title></title>
</head>
<body>
  <form id="MengXianhuiForm" runat="server">
  <asp:TextBox ID="TextBox1" runat="server" Text="能输入文字吗"></asp:TextBox>
  <asp:ListBox ID="ListBox1" runat="server">
    <asp:ListItem>AA</asp:ListItem>
    <asp:ListItem>BB</asp:ListItem>
  </asp:ListBox>
  <asp:GridView ID="GridView1" runat="server">
    <Columns>
      <asp:TemplateField>
        <ItemTemplate>
          <asp:TextBox ID="x" runat="server" Text="测试" />
        </ItemTemplate>
      </asp:TemplateField>
    </Columns>
  </asp:GridView>
  <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="设置页面中的所有控件的 Enabled 属性" />
  </form>
</body>
</html>

作者 孟宪会
补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,