2011-07-24 31 views
1

我想問我是否可以在我的控件中循環,如文本框,下拉列表等等,它們在頁面的用戶控件中。這種情況是,假設我有一個名爲'Page.aspx'的頁面,並且在page(uc1, uc2 and uc3)中有3個用戶控件,並且在每個用戶控件中包含一個asp面板(名爲PnlTab1)以包含所有這些控件。 我使用的代碼來達到我的控件:如何在多用戶控件中循環控制?


  UserControl uc1, uc2, uc3; 
      uc1 = usercontrol1; 
      uc2 = usercontrol2; 
      uc3 = usercontrol3; 

      foreach (Control c in uc1.FindControl("PnlTab1").Controls) 
      { 
       if (c is TextBox) 
        ((TextBox)c).Enabled = true; 
      } 

      foreach (Control c in uc2.FindControl("PnlTab1").Controls) 
      { 
       if (c is TextBox) 
        ((TextBox)c).Enabled = true; 
      } 
      foreach (Control c in uc3.FindControl("PnlTab1").Controls) 
      { 
       if (c is TextBox) 
        ((TextBox)c).Enabled = true; 
      } 

現在,我不想每次都「foreach (Control c in uc3.FindControl("PnlTab1").Controls」寫的。我可以遞歸地做到這一點嗎?

謝謝大家!

回答

0

不需要遞歸,只是另一種循環:

UserControl[] ucs = new UserControl[3]{ 
     usercontrol1, 
     usercontrol2, 
     usercontrol3 
    }; 
    foreach (UserControl uc in ucs){ 
     foreach (Control c in uc.FindControl("PnlTab1").Controls) 
     { 
      if (c is TextBox) 
       ((TextBox)c).Enabled = true; 
     } 
    } 
+0

謝謝你的回答,Tim,Dave和TheGeekYouNeed。 – enginbilici

+0

我無法將用戶控件聲明爲數組。有這麼多的錯誤發生時,我試試這個。不幸的是,我遠程連接到我的程序,並有連接問題。我明天再試一次。謝謝你的回答。 – enginbilici

+0

對不起,我在那裏閃回了c。這個新的語法應該是正確的。 – Dave

1

下面是如何遞歸執行的一個例子。

通爲您的控件容器(頁是一個有效的控制)

public static void DisableAllChildServerControls(Control ctrl, bool disable) 
    { 
     foreach(Control c in ctrl.Controls) 
     { 
      if (c is TextBox) 
      { 
       TextBox t = c as TextBox; 
       t.Enabled = !disable; 
       if (t.ID == "txtRefundedAmount") 
        t.Enabled = true; 
      } 
      else if (c is DropDownList) 
      { 
       DropDownList d = c as DropDownList; 
       d.Enabled = !disable; 
      } 
      else if (c is Button) 
      { 
       Button b = c as Button; 
       b.Enabled = !disable; 
      } 

      if(c.Controls.Count > 0) 
      { 
       DisableAllChildServerControls(c, disable); 
      } 
     } 
    } 
+0

感謝您的回答,我有一些連接問題我的遠程連接,我會稍後再嘗試。我會分享結果。再次感謝..! – enginbilici

1

.NET不(據我所知)支持遞歸的FindControl,但它可以實現自己。史蒂夫·史密斯有一個:Recursive FindControl

它使用泛型的好處,所以你可以這樣做:

// uc3 has id = "UserControl1" 
TextBox tb = FindControl<TextBox>(UserControl1, "PnlTab1"); 
if (tb != null) 
{ 
    tb.Enabled = true; 
} 

看看他的文章,看看它是否適合你的需要。

+0

感謝您的回答,我的遠程連接有一些連接問題,我稍後再嘗試。我會分享結果。再次感謝..! – enginbilici

+0

不客氣:) – Tim