我正在尝试在ASP.NET中创建一个新的服务器控件类型。此控件将RequiredFieldValidator放入某个位置。我的类继承自WebControl类,它有一个ControlID属性,它是给定控件的ID。将使用给定的ControlID在控件附近生成RequiredFieldValidator。但是,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" />
我已经搜索并尝试了几个小时但没有运气。任何人都可以告诉我是什么原因导致这种行为以及为什么,是否有人对解决方案有一些建议?提前谢谢
答案 0 :(得分:2)
ControlID必须公开才能生效;它无法保护,可以通过标记进行设置。