asp.net 遍历aspx页面中的TextBox控件,并设置属性为只读

aspx页面中的代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="遍历页面所有某一类型的控件.WebForm1" %> 

<!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">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server">1</asp:TextBox>
<br />
<p></p>
<asp:TextBox ID="TextBox2" runat="server">2</asp:TextBox>
<br />
<p></p>
<asp:TextBox ID="TextBox3" runat="server">3</asp:TextBox>
<br />
<p></p>
<asp:TextBox ID="TextBox4" runat="server">4</asp:TextBox>
<br />
<p></p>
</div>
</form>
</body>
</html>

方法1:

for (int i = 0; i < Page.Controls.Count; i++) 
{
foreach (System.Web.UI.Control stl in Page.Controls[i].Controls)
{
Response.Write(stl.ToString() + "<br/>");
if (stl is TextBox)
{
TextBox tb = (TextBox)stl;
tb.ReadOnly = true;
}
}
}

方法2:

foreach(System.Web.UI.Control stl in this.Form.Controls) 
{
Response.Write(stl.ToString()+"<br/>");
if(stl is System.Web.UI.WebControls.TextBox)
{
TextBox tb = (TextBox)stl;
tb.ReadOnly = true;
}
}


先获取页面上所有的控件(包括客户端和服务器端控件)--- this.Form.Controls

先过滤得到服务器 --- is System.Web.UI.WebControls.TextBox

强制转换为TextBox控件 ---TextBox tb = (TextBox)stl;

设置属性 ---tb.ReadOnly = true;

你可能感兴趣的:(asp.net)