2011-02-04 69 views
1

我想在Page_Load中隱藏我所有的RadioButtonLists但我似乎無法得到語法完全正確ASP.NET找到網頁上的所有控件,並隱藏他們

我猜我有使用FindControl語法像這樣

CType(FindControl, RadioButtonList) 

然後我猜我會通過每個單選按鈕列表必須循環,並設置Visible = False屬性就可以了。

我似乎得到上面的代碼錯誤。

任何想法我可以嘗試嗎?

感謝

回答

1

FindControl只在您知道要查找的控件的名稱時起作用,並且不僅僅是遞歸調用。除非您可以保證您的控件將位於您正在搜索的特定容器中,否則您將無法找到它。如果你想查找所有的單選按鈕列表,你需要編寫一個循環遍歷父/子關係中所有控件集的方法,並將單選按鈕列表設置爲false。

只是通過Page.Controls這個功能(未經測試,可能需要的調整):

public void HideRadioButtonLists(System.Web.UI.ControlCollection controls) 
{ 
    foreach(Control ctrl in controls) 
    { 
     if(ctrl.Controls.Count > 0) HideRadioButtonLists(ctrl.Controls); 
     if("RadioButtonList".Equals(ctrl.GetType().Name, StringComparison.OrdinalIgnoreCase)) 
      ((RadioButtonList)ctrl).Visible = false; 
    } 
} 
+0

感謝那正是我之後 – 2011-02-04 14:49:10

0

爲什麼不使用ASP.Net皮膚頁面爲所有RadioButtonLists的默認值設置爲可見=假。

我會def看看在這裏使用皮膚頁面。

3

試試這個:

protected void Page_Load(object sender, EventArgs e) 
{ 
    HideRadioButtonLists(Page.Controls); 
} 

private void HideRadioButtonLists(ControlCollection controls) 
{ 
    foreach (WebControl control in controls.OfType<WebControl>()) 
    { 
     if (control is RadioButtonList) 
      control.Visible = false; 
     else if (control.HasControls()) 
      HideRadioButtonLists(control.Controls); 
    } 
} 
0

做的控件屬性的foreach和檢查的類型將是慢。在我看來,根據你的要求,你應該做的是使用CSS /皮膚來隱藏不需要的按鈕,或者簡單地將它們添加到List<T>,這樣你就可以只遍歷那些需要修改的按鈕。

最糟糕的情況是foreach會起作用,但這有點慢並且不可取。