我正在尝试在 ASP.NET 中创建新的服务器控件类型。此控件会将RequiredFieldValidator 放入某个位置。我的类继承自 WebControl 类,它有一个 ControlID 属性,它是给定控件的 ID。RequiredFieldValidator 将在具有给定 ControlID 的控件附近生成。但是,ControlID 的值是什么。在什么情况下我可以成功使用这个属性?
Public Class MyControl
Inherits WebControl
'...
Protected Property ControlID As String
Protected Property IsLinkedBrother As Boolean = False
'...
Protected Overrides Sub OnPreRender(e as System.EventArgs)
MyBase.OnPreRender(e)
Dim rootControl = If(IsLinkedBrother, Parent, Page)
Dim controls As Stack(Of Control) = New Stack(Of Control)
Dim currentControl As Control = Nothing
controls.Push(rootControl)
Dim result As Control = Nothing
While ((result Is Nothing) AndAlso (controls.Count > 0))
currentControl = controls.Pop
If ((Not String.IsNullOrEmpty(currentControl.ID)) AndAlso (currentControl.ID.Equals(ControlID))) Then
result = currentControl
Else
For Each child As System.Web.UI.Control In currentControl.Controls
controls.Push(child)
Next
End If
End While
'...
End Sub
'...
End Class
但是由于某种原因 ControlID 是 Nothing 并且该事件引发异常。ControlID 在初始化后永远不会改变,它是这样初始化的:
<MyControl runat="server" ID="IDValue" ControlID="ControlIDValue" EnableCliendScript="true"
CssClass="Whatever" Display="Dynamic" />
我已经搜索并尝试了几个小时,但没有运气。谁能告诉我什么会导致这种行为以及为什么,有人对解决方案有一些建议吗?先感谢您