【问题标题】:Access placeholders in a loop循环访问占位符
【发布时间】:2014-09-03 15:25:09
【问题描述】:

我需要在 C# 的循环中动态创建占位符的名称,但我不知道如何获得正确的名称。

占位符在 aspx 页面中设置,currMaxValues 是最大值。占位符集的数量。

我当前的标记:

const int currMaxValues = 6;

        for (int i = 0; i < currMaxValues; i ++)
        {
            //new placeholdernames
            string currPlaceholderTime = "placeholderTime" + i;
            string currPlaceholderMore = "placeholderZusatz" + i;
            string currPlaceholderIco = "placeholderIco" + i;
            string currPlaceholderTemp = "placeholderTemp" + i;

            //elements for placeholders
            Label time = null;
            Label more = null;
            Image img = null;
            Label temp = null;

            //built the stuff for the placeholders
            DateTime currTime = DateTime.Now;
            int hour = currTime.Hour;
            time.Text = hour.ToString();

            //(PlaceHolder)currPlaceholderTime.Controls.add(time);
        }

是否可以使用我在循环开始时创建的占位符的名称来访问控件?

感谢您的帮助!

【问题讨论】:

    标签: c# asp.net placeholder


    【解决方案1】:

    您必须使用 FindControl 函数来查找具有如下动态 id 的控件

    FindControl("controlname")
    

    在您的情况下,您需要更改以下代码

    for (int i = 0; i < currMaxValues; i ++)
            {
                //new placeholdernames
                string currPlaceholderTime = "placeholderTime" + i;
                string currPlaceholderMore = "placeholderZusatz" + i;
                string currPlaceholderIco = "placeholderIco" + i;
                string currPlaceholderTemp = "placeholderTemp" + i;
    
                //elements for placeholders
                Label time = null;
                Label more = null;
                Image img = null;
                Label temp = null;
    
                //built the stuff for the placeholders
                DateTime currTime = DateTime.Now;
                int hour = currTime.Hour;
                time.Text = hour.ToString();
    
                Placeholder placeHolderTime = FindControl(currPlaceholderTime) as PlaceHolder;
                placeHolderTime.Controls.Add(time);
    
                //(PlaceHolder)currPlaceholderTime.Controls.add(time);
            }
    

    但是请注意,上述代码仅在您的页面不在母版页下或占位符直接在主页下时才有效。 如果上面的代码找不到,你需要一个类似下面的函数,分层查找控件。

    private Control FindControl(Control rootControl, string controlID)
      {
       if (rootControl.ID == controlID) return rootControl;
    
       foreach (Control controlToSearch in rootControl.Controls)
       {
        Control controlToReturn =
         FindControl(controlToSearch, controlID);
        if (controlToReturn != null) return controlToReturn;
       }
       return null;
      }
    

    那么你就可以使用下面的代码调用上面的函数来查找占位符了

    Placeholder placeHolderTime = FindControl(this,currPlaceholderTime) as PlaceHolder;
    

    【讨论】:

      猜你喜欢
      • 2013-09-07
      • 2014-09-25
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      相关资源
      最近更新 更多