在循环中访问占位符

时间:2014-07-13 15:23:53

标签: c# asp.net placeholder

我需要在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);
        }

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

感谢您的帮助!

1 个答案:

答案 0 :(得分: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;