我试图弄明白这是怎么做到的,我想我已经找到了解决办法。
可以在ASPX端定义控件的属性。如果控件是
WebControl
(许多控件(如文本框、标签、按钮等)是WebControls,但某些数据绑定控件(如中继器、GridView)则不是)。通过使用这些信息,我编写了一个递归方法。在这里,它的用法是:
First Name
<asp:TextBox runat="server" ID="tbxFirstName" ControlGroup="Editable" />
<asp:Label runat="server" ID="lblFirstName" ControlGroup="ReadOnly" />
Last Name
<asp:TextBox runat="server" ID="tbxLastName" ControlGroup="Editable" />
<asp:Label runat="server" ID="lblLastName" ControlGroup="ReadOnly" />
<asp:Button ID="btn" runat="server" Text="Do" OnClick="btn_Click" />
代码隐藏:
protected void btn_Click(object sender, EventArgs e)
{
var controlsOfGroupReadonly = ControlsInGroup("Readonly");
}
protected IEnumerable<WebControl> FindControlsInGroup(Control control, string group)
{
WebControl webControl = control as WebControl;
if (webControl != null && webControl.Attributes["ControlGroup"] != null && webControl.Attributes["ControlGroup"] == group)
{
yield return webControl;
}
foreach (Control item in control.Controls)
{
webControl = item as WebControl;
if (webControl != null && webControl.Attributes["ControlGroup"] != null && webControl.Attributes["ControlGroup"] == group)
{
yield return webControl;
}
foreach (var c in FindControlsInGroup(item, group))
{
yield return c;
}
}
}
protected IEnumerable<WebControl> ControlsInGroup(string group)
{
return FindControlsInGroup(Page, group);
}
我不知道是否有方法可以将此方法转换为索引器。
我试过了,结果对我来说是成功的。
这是个好问题。谢谢:)