Control Search

  • Thread starter Thread starter bannaman
  • Start date Start date
B

bannaman

I have a function below which is searching for a control on a page.
When i debug this function the first time it worked fine when i was
stepping through it then when i tried it again it error with the error
of object not set to an instance of an object I didn't change anything
between the two debugging attempts does any one know why it would
error.



Public Function getControl(ByVal theControl As ControlCollection, ByVal
toFind As String) As Control

Dim ctrl As Control = Nothing

For i As Integer = 1 To theControl.Count - 1
'If Not theControl.Item(i) Is Nothing Then
If theControl.Item(i).ID.ToString.ToUpper = toFind.ToUpper
Then
ctrl = theControl.Item(i)
Exit For
End If
'End If
Next

Return (ctrl)

End Function
 
you can write that much more elegantly using a foreach and making proper use
of return

foreach control as Control in theControl
if control.ID.ToString.ToUpper = toFind.ToUpper then
return control
end if
next
return nothing

It's hard to see where your error is without knowing more about the context.
which line is giving the null reference? My guess is that theControl is
nothing, so when you do theControl.Count you get an error.

Karl
 
Thanks for your response. it errors on the line. The parameter
theControl is populated when it is passed into the function but
something odd goes on after this

If theControl.Item(i).ID.ToString.ToUpper = toFind.ToUpper
 
It's possible that the control collection is being modified, though I doubt
that.

it is possible for ID to be nothing, so doing ID.ToString() might cause the
error. This is especially true if the control is being dynamically
added..though it might happen in other cases. If you debug your code, it
should be easy for you to figure out what value is nothing.

On a side note, if you have a parent control, you can simply do,
parentControl.FindControl("ID")

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top