以上代码运行结果如下:
A List of the Controls in the Controls Collection
3、动态地创建控件、遍历创建的控件以及改变控件属性的一个应用。
用户输入一个1-10的整数,按按钮后动态创建相应数字的TextBox。代码如下:
System.Web.UI.LiteralControl
System.Web.UI.WebControls.Label
System.Web.UI.LiteralControl
System.Web.UI.HtmlControls.HtmlForm
System.Web.UI.LiteralControl
System.Web.UI.WebControls.TextBox
System.Web.UI.LiteralControl
System.Web.UI.ResourceBasedLiteralControl
这下TextBox控件真的露出了庐山真面目。
script runat="server" language="C#">
int count = 1;
void IterateThroughChildren(Control parent) //遍历所有控件
{
foreach (Control c in parent.Controls)
{
if (c.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox") &&
c.ID == null) //找到所有新创建的TextBox控件(新创建的TextBox的ID为空,有别于页面中id="txtTBCount"的TextBox)
{
((TextBox) c).Text = "TextBox " + count.ToString(); //改变TextBox的属性。
((TextBox) c).Columns = 10; //改变TextBox的属性
count++; //count为全局变量,记录找到的TextBox数量
}
if (c.Controls.Count > 0)
{
IterateThroughChildren(c);
}
}
}
void CreateTextBoxes(Object sender, EventArgs e) //按下按钮激活的事件
{
if (!Page.IsValid) return;
int n = Int32.Parse(txtTBCount.Text); //取得用户输入的数字。
//创建n个TextBox,并把它们加到PlaceHolder里面
for (int i = 0; i < n; i++)
{
TextBoxesHere.Controls.Add(new TextBox());
}
//遍历并设置每个TextBox的属性
IterateThroughChildren(this);
}
</script>
<form runat="server">
How many TextBoxes would you like to create? (<i>Please choose vaule between 1 and 10</i>)<br />
<asp:textbox runat="Server" id="txtTBCount" Columns="3" />
<asp:RangeValidator runat="server" ControlToValidate="txtTBCount"
MinimumValue="1" MaximumValue="10" Type="Integer"
ErrorMessage="Make sure that you choose a value between 1 and 10!" />
<br />
<asp:button runat="server" Text="Create Dynamic TextBoxes"
OnClick="CreateTextBoxes" />
<p>
<asp:PlaceHolder runat="server" id="TextBoxesHere" />
</form>