我需要在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的名称来访问控件?
谢谢你的帮助!
您必须使用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;