Changing property of multiple ASP.NET controls in one operation
I was wondering whether in ASP.NET it 开发者_开发技巧is possible to change properties of bunch of controls in one operation. Of course there are probably many ways around this, but does anybody know an elegant solution to this?
Example pseudo-code
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" />
protected void ChageMode(bool isReadOnly)
{
ControlGroups["Editable"].ForEach(c => c.Visible = !isReadOnly);
ControlGroups["ReadOnly"].ForEach(c => c.Visible = isReadOnly);
}
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 :)
you can do something similar to:
pnl.Controls.OfType()
.ToList()
.ForEach(t => { t.ReadOnly = yourChoose; t.Text = yourValue; } );
this piece of code search for every textbox in your page (then change readonly and text properties)
精彩评论