1

I need to find a control in one page but I don't know the complete ID. I only know a part of the ID.

What I wan't to do is something like this:

control = Page.FindControl(part1 & part2)

Where part1 is the known part of the ID and part2 is the unknown part.

ps2goat
  • 8,067
  • 1
  • 35
  • 68
burk15
  • 23
  • 4

1 Answers1

1

For what it's worth, you could use this extension method which searches all child controls:

Module ControlExtensions
    <Runtime.CompilerServices.Extension()>
    Public Function FindControlPart(root As Control, IdStart As String) As Control
        Dim controls As New Stack(Of Control)(root.Controls.Cast(Of Control)())
        While controls.Count > 0
            Dim currentControl As Control = controls.Pop()
            If currentControl.ID.StartsWith(IdStart, StringComparison.InvariantCultureIgnoreCase) Then
                Return currentControl
            End If
            For Each child As Control In currentControl.Controls
                controls.Push(child)
            Next
        End While
        Return Nothing
    End Function
End Module

Usage:

Dim control As Control = Page.FindControlPart(part1)

It returns the first control which start with a given ID-Part. So it's possible that you get the wrong. It's less error-prone if you use the correct NamingContainer instead of the Page as root.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Yes, this can be a good solution, but I don't want to go through all the controls because there are a lot. I need to get the control without going through all the controls of the page – burk15 Oct 28 '14 at 14:29
  • @burk15: please read my last sentence again ;-) If you know the parent control use that as root. But note that you have a problem if you're searching in a `GridView` and you don't have the correct `GridViewRow`. – Tim Schmelter Oct 28 '14 at 14:32
  • ASP.NET webforms does the same thing to find controls (loop through them). – ps2goat Oct 28 '14 at 14:37
  • @ps2goat: ASP.NET `FindControl` does not search controls recursively(incl. child-controls) as my method does. [`Control.FindControl`](http://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx) just searches the current `NamingContainer`. – Tim Schmelter Oct 28 '14 at 14:40
  • @TimSchmelter, I wasn't saying your code was wrong, I meant that there was no need to fear the looping. You are correct that ASP.NET only searches through the first level children. – ps2goat Oct 28 '14 at 15:10