2010-09-23 59 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

相關問題