I ran into a situation where FindControl
was returning a control that wasn't a complete match of the Id I was searching by. There are two controls in the parentcontrol with similar Ids like: "MyControl" and "MyControlAlternate". When I call FindControl
("MyControl") the control returned is "MyControlAlternate". I was wondering if anyone had any explaination why or thoughts as to what might be causing this problem. The way I got around this was implementing my own version of FindControl
.
views:
74answers:
1
+1
A:
The default behavior of FindControl to use its own naming container. If that doesn't work it tries to do pattern matching on the name. That would explain why you are getting the wrong control - your naming container is incorrect and the code is making it into the pattern matching phase.
Here is the dissassembly of FindControl from Reflector:
Public Overridable Function FindControl(ByVal id As String) As Control
Return Me.FindControl(id, 0)
End Function
Protected Overridable Function FindControl(ByVal id As String, ByVal pathOffset As Integer) As Control
Dim str As String
Me.EnsureChildControls
If Not Me.flags.Item(&H80) Then
Dim namingContainer As Control = Me.NamingContainer
If (Not namingContainer Is Nothing) Then
Return namingContainer.FindControl(id, pathOffset)
End If
Return Nothing
End If
If (Me.HasControls AndAlso (Me._occasionalFields.NamedControls Is Nothing)) Then
Me.EnsureNamedControlsTable
End If
If ((Me._occasionalFields Is Nothing) OrElse (Me._occasionalFields.NamedControls Is Nothing)) Then
Return Nothing
End If
Dim anyOf As Char() = New Char() { "$"c, ":"c }
Dim num As Integer = id.IndexOfAny(anyOf, pathOffset)
If (num = -1) Then
str = id.Substring(pathOffset)
Return TryCast(Me._occasionalFields.NamedControls.Item(str),Control)
End If
str = id.Substring(pathOffset, (num - pathOffset))
Dim control2 As Control = TryCast(Me._occasionalFields.NamedControls.Item(str),Control)
If (control2 Is Nothing) Then
Return Nothing
End If
Return control2.FindControl(id, (num + 1))
End Function
Clearly what is happening in your example is that you are not specifying the correct naming container. However, without providing a code example I cannot be more specific than this.
NightOwl888
2010-10-18 17:40:02
Based on what you are saying is the plausible cause that would make total sense. Thank you for a great answer
Achilles
2010-10-21 17:45:02