.net反射之使用反射技术为控件赋值

时间:2021-04-05 21:56:11


前台页面

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

        <asp:Button ID="Button1" runat="server" Text="赋值" onclick="Button1_Click" />

    </div>
    </form>
</body>
</html>


后台代码

  protected void Button1_Click(object sender, EventArgs e)
   {
           for (int i = 1; i <= 2; i++)
           {
               //通过反射获得控件对象
                object o = this.GetType().GetField("TextBox" + i.ToString(), BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this);
                TextBox text = (TextBox)o;

                text.Text = "你好"; //这样通过循环,实现了对这10个TextBox控件的赋值
           }
 }