簡體   English   中英

遍歷頁面控件-對多個控件類型使用相同的邏輯

[英]looping through Page Controls - using same logic for multiple control types

我正在像這樣遍歷頁面控件

      foreach (Control ctrl in control.Controls)
      {
          if (ctrl is System.Web.UI.WebControls.TextBox || ctrl is System.Web.UI.WebControls.Label)
          {
          }
      }

我希望能夠在此if語句中聲明與foreach中的“ ctrl”類型相同的變量,以便我可以檢查控件的屬性並以此方式執行一些操作。 我不想重復代碼,例如,如果“ ctrl”是文本框或標簽,因為我將對這兩種Web控件類型執行相同的代碼。

任何幫助我朝正確方向前進的幫助,我們將不勝感激!

謝謝

嘗試使用ITextControl接口:

foreach (Control ctrl in control.Controls)
{
    ITextControl text = ctrl as ITextControl;
    if (text != null)
    {
        // now you can use the "Text" property in here,
        // regardless of the type of the control.
    }
}

您還可以在此處使用OfType擴展方法來對此進行清理:

foreach (ITextControl text in control.Controls.OfType<ITextControl>())
{
    // now you can use the "Text" property in here,
    // regardless of the type of the control.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM