I was trying to figure out how this can be done and I think I have found a solution.
You can define Attributes on Controls in aspx side. You also can query these attributes if the control is WebControl
(many controls such as TextBox, Label, Button etc are WebControls, but some databound controls like Repeater, GridView are not). By using this information I wrote a recursive method. Here it is, with its usage:
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" />
Code behind:
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);
}
I don't know if is there a way to convert this method to an indexer.
I have tried and the result was successfull for me.
It was a good question. Thanks :)