查找嵌套在Repeater Control中的控件
我试图找到通过 UserControl在Repeater中呈现的TextBoxes的值,即Repeater有UserControl的占位符,而UserControl内部是TextBox标记实际存在的位置。 我以前用直接在 Repeater 里面的TextBoxes做过这个,这是相当直接的,我想知道为什么这显然不能以同样的方式完成。 这是带有Repeater的Default页面,其中包含一个Placeholder …
…以及插入Placeholder位置的UserControl …
…但是当以下代码运行Display按钮的OnClick时,我总是得到UserControl中任何和所有TextBoxes(和DropDowns)的空值…
protected void DisplayEntries(object sender, EventArgs e) { foreach (RepeaterItem repeated in rptBudget.Items) { TextBox txtPercentage = (TextBox)repeated.FindControl("txtPercentage"); if (txtPercentage == null) { lblCtrls.Text += " null; "; } else { lblCtrls.Text += txtPercentage.Text + "; "; } } }
访问这些值的最佳方法是什么? 谢谢。
txtPercentage Textbox位于Usercontrol内,因此请使用以下帮助程序方法来检索它。
助手方法
public static Control FindControlRecursive(Control root, string id) { if (root.ID == id) return root; return root.Controls.Cast() .Select(c => FindControlRecursive(c, id)) .FirstOrDefault(c => c != null); }
用法
foreach (RepeaterItem repeated in rptBudget.Items) { TextBox txtPercentage = (TextBox)FindControlRecursive(repeated, "txtPercentage"); ... }
您需要首先获取UserControl, 然后在UC本身上使用FindControl
。
首先尝试加载占位符,然后在占位符中查找文本框:
像这样的东西:
伪
var ph = repeated.FindControl("phBudget"); var txtBox = ph.FindControl("txtPercentage");
/伪