页面生命周期 – 使用FindControl引用在页面加载期间以编程方式创建的控件

我正在以编程方式在我的表单上创建一些文本框,稍后我需要使用FindControl来引用它。

我在创建它们的代码之后将FindControl指令放在页面加载方法中,但是得到了一个错误:

你调用的对象是空的。

我假设这是因为文本框控件直到生命周期的后期才创建,因此无法从Page_Load中引用。

有人可以建议我的代码隐藏在哪里,我需要放置FindControl指令,以便它可以找到这些以编程方式创建的文本框?

您是否将文本框控件放在另一个控件(如面板或网格)中? 如果是这样,您需要递归搜索页面上的所有控件。

下面是递归FindControl实现的示例: 递归Page.FindControl 。 您可以通过Google搜索“recursive findcontrol”找到许多其他示例。

如果以编程方式创建文本框,则可以直接使用它来操作它们。 不需要FindControl(也会更慢)

TextBox txt = new TextBox(); ... txt.Text = "Text"; 

如果您需要使用不同的方法访问,您可以将txt设为类的私有变量。

如果你真的需要使用FindControl – 当你调用函数时,是否在页面中添加了文本框(添加到页面的Controls列表中)?

在页面加载时,控件应全部设置好并准备好使用。 初始化控制并在启动阶段(在加载阶段之前)进行初始化。

我建议你检查代码找到控件开始 – 例如,如果控件嵌套在其他控件中,你将需要递归搜索或从正确的容器控件。

如果要在CreateChildControls中添加文本框,则可能必须在访问它们之前调用EnsureChildControls。

刚从Steele Price的博客文章中找到了这个function,它完美无缺。 我试图在具有母版页的页面中引用用户控件,除此之外我没有尝试过任何工作。 把它放在你的一个核心课程中。 阅读Steele的博客文章了解更多详情。

如果你把它放在一个类中,你需要得到控件参考,如:

 Dim imgStep2PreviewIcon As Image = Eyespike.Utilities.FindControl(Of Control)(Page, "imgStep1PreviewIcon") imgStep2PreviewIcon.Visible = False 

VB.NET代码

 Public Shadows Function FindControl(ByVal id As String) As Control Return FindControl(Of Control)(Page, id) End Function Public Shared Shadows Function FindControl(Of T As Control)(ByVal startingControl As Control, ByVal id As String) As T Dim found As Control = startingControl If (String.IsNullOrEmpty(id) OrElse (found Is Nothing)) Then Return CType(Nothing, T) If String.Compare(id, found.ID) = 0 Then Return found For Each ctl As Control In startingControl.Controls found = FindControl(Of Control)(ctl, id) If (found IsNot Nothing) Then Return found Next Return CType(Nothing, T) End Function 

C# (未经测试,使用converter.telerik.com生成)

 public new Control FindControl(string id) { return FindControl(Page, id); } public static new T FindControl(Control startingControl, string id) where T : Control { Control found = startingControl; if ((string.IsNullOrEmpty(id) || (found == null))) return (T)null; if (string.Compare(id, found.ID) == 0) return found; foreach (Control ctl in startingControl.Controls) { found = FindControl(ctl, id); if ((found != null)) return found; } return (T)null; } 

如果你在OnInit覆盖期间(在我相信调用base.OnInit(e)之前)创建TextBox控件,它们将在Page.OnLoad和任何相关事件期间可用。 您还可以将它们放入ViewState对象图中的正确位置,这对于处理回发特别是服务器端validation非常有用。