麻烦的FindControl和动态地创建的控件 [英] Trouble with FindControl and dynamicly created controls
问题描述
举例code:
var div = new HtmlGenericControl("div");
div.Controls.Add(new Literal() { ID = "litSomeLit" });
var lit = (Literal)div.FindControl("litSomeLit");
Assert.IsNotNull(lit);
这code不能断言,因为点亮为空。调试表明,div.Controls肯定包含的ID文字litSomeLit。我的问题是为什么?和有没有办法让一个特定ID的控制,而在同一时间一个元素做递归搜索div.Controls []的手?
This code fails the assert, because lit is null. Debugging shows that div.Controls definitely contains a literal with ID of "litSomeLit." My questions are "Why?" and "Is there any way to get a control of a specific ID without doing a recursive search of div.Controls[] by hand one element at a time?"
我正在做的事情这种方式的原因是,我的实际应用是不那么straightforward-方法我写给出用在许多可能的配置几个子控件一个复杂的控制。我需要访问特定的控制几层下来(例如,ID为txtSpecificControl控制可能会在 StartingControl.Controls [0] .Controls [2] .Controls [1] .Controls [3]
)。通常情况下我可以做的FindControl(txtSpecificControl)
,但这似乎并没有在刚刚动态创建的控件(如上面的例子中code)工作
The reason I'm doing things this way is that my actual application is not so straightforward- a method I'm writing is given a complex control with several subcontrols in a number of possible configurations. I need to access a specific control several layers down (eg, the control with ID "txtSpecificControl" might be at StartingControl.Controls[0].Controls[2].Controls[1].Controls[3]
). Normally I could just do FindControl("txtSpecificControl")
, but that does not seem to work when the controls were just dynamically created (as in the above example code).
推荐答案
近,我可以告诉,有没有办法做什么,我试图完成无添加控件的页面。如果我猜,我想说的FindControl使用该控件,它通常包含的所有控件的上方当前的ID(如OuterControlID $ LowerControlId $的TargetControlID)的UniqueID属性。当控制实际上被添加到网页,将只得到生成的。
Near as I can tell, there is no way to do what I'm trying to accomplish without adding the control to the page. If I had to guess, I'd say that FindControl uses the UniqueID property of the control, which generally contains the IDs of all the controls above the current one (eg OuterControlID$LowerControlId$TargetControlID). That would only get generated when the control actually gets added to the page.
总之,这里的递归深度优先搜索的实现的FindControl当控件没有连接到页面然而这会工作:
Anyway, here's an implementation of recursive depth-first-search FindControl that'll work when the control is not attached to the page yet:
public static Control FindControl(Control parent, string id)
{
foreach (Control control in parent.Controls)
{
if (control.ID == id)
{
return control;
}
var childResult = FindControl(control, id);
if (childResult != null)
{
return childResult;
}
}
return null;
}
这篇关于麻烦的FindControl和动态地创建的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!