2010-09-23 77 views
1

我想知道在ASP.NET中是否可以在一个操作中更改一组控件的属性。当然,可能有很多方法可以解决这个问题,但有没有人知道一个优雅的解决方案呢?在一个操作中更改多个ASP.NET控件的属性

示例伪代码

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); 
} 

回答

1

我想知道如何做到这一点,我想我已经找到了解决方案。 您可以在aspx端定义控件的属性。如果控件是WebControl(许多控件(如TextBox,Label,Button等等)都是WebControls,但是某些数据绑定控件(如Repeater,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); 
} 

我不知道有没有办法这种方法转换为索引。

我试过了,结果对我来说是成功的。

这是一个很好的问题。感谢:)

+0

我认为根控制也应该移到参数中,因为你可能想在FormView前进行搜索进入模板领域也是一个值得解决的问题。 – 2010-09-23 13:39:56

+0

你确实是对的。但是FindControlsInGroup方法可以完成你所说的。您可以将任何控件作为参数传递,并返回该组中的控件。可能我们可以给ControlsInGroups和FindControlsInGroup方法赋予相同的名称作为重载。 – 2010-09-23 13:53:49

1

你可以做类似的东西:


       pnl.Controls.OfType() 
        .ToList() 
        .ForEach(t => { t.ReadOnly = yourChoose; t.Text = yourValue; }); 

这段代码搜索的在你的页面的每个文本框(然后更改只读和文本属性)

+0

是的,这是直接的解决方案,但我感兴趣的是,ASP.NET是否有一些本机的东西或一个解决方案,需要较少的代码(在这里你没有考虑到控制可以嵌套) – 2010-09-23 09:01:41

相关问题