Saturday, February 10, 2007

"FindControl" a waste?*

Saturday, February 10, 2007 12:21:48 AM (GMT Standard Time, UTC+00:00)

It's been a while since I've posted anything related to my "professional" life... but alas I'm back, and sad to say, on a sour note!

This time I'm commenting on the "Control.FindControl Method (String)". This method just works.. soo.. unreliably! At first, I thought I was making some mistake in understanding its purpose but it clearly states on MSDN "Searches the current naming container for a server control with the specified id parameter.", so I'm left to wonder if it is a waste. I mean, I remember it working before.. but it refuses to work now!

My problem has come in my trying to find a control within a ContentTemplate (Read a bit more on that here) which I can clearly find if I loop through the collection of contained controls in the Controls property (of the template). When I try to use the FindControl method, the return value is a persistent "Nothing". I also have checked online for this problem and a number of other sites, especially forums have had persons complaining about it. One I quite like is this one, where the guy asking for help is absurdly sarcastic when he doesn't get his questions answered. Ways.. I've decided that if I'm looking for a control in a container the most reliable path is to do the following.

'Creating reference to desired control
Dim dControl As UI.WebControls.Xml = Nothing

'Looping through container to find desired control
For Each ctrl As Web.UI.Control In tempContainer.Controls

   'If control has been found.. btw control is identified by its ID, in this case, "Xml1"
   If ctrl.ID = "Xml1" Then
      'Save control since it has been found. Of course Ctype it first..
      dControl = CType(ctrl, UI.WebControls.Xml)      
      Exit For
   End If
Next

(i.e. loop through the controls manually... after all, this is what's being done by the FindControl method anyway! In my case, it's only about 3 or so more LOC.)

Related posts:
Select a random row in MS SQL...
Regular expressions
VS2005, ASP.NET 2 & DLLs, DLLs..
MS's ASP.NET and.. PHP
2-way databinding cascading drop down lists within a FormView
ApplicationName Property when customising providers

Comments are closed.