Iterate through page controls

  • Thread starter Thread starter Avon
  • Start date Start date
A

Avon

Hi friends,
I need of some help,
I have this code:
For Each t As TextBox In Page.Controls ' here is the error
t.Text = "test"
Next

But I am getting this error:
Unable to cast object of type 'ASP.masterpages_maindesign_master' to type
'System.Web.UI.WebControls.TextBox'.
Please help me to understand this error and solve the problem
Thanks in advance
 
Hi,

Many ways to resolve this, if you understand why the error occurs.
Basically the Page can have a lot of objects and when iterating through
them, the "masterpages_maindesign_master" object is also encountered.
Since it is not a TextBox, the exception results when your code tries
to convert it to a TextBox. So, basically you need to check if it is a
TextBox, before trying to convert it to a TextBox or query it's Text
property.

Instead, you could use :

For Each o As Object In Page.Controls
If TypeOf (o) Is TextBox Then
t.Text = "test"
End if
Next

HTH,

Regards,

Cerebrus.
 
Avon said:
For Each t As TextBox In Page.Controls
t.Text = "test"
Next

But I am getting this error:
Unable to cast object of type 'ASP.masterpages_maindesign_master' to type
'System.Web.UI.WebControls.TextBox'.
Please help me to understand this error and solve the problem

Not every control on the page is a TextBox.

Your code says
For Each t As TextBox In Page.Controls

which tells VB to go and get each control in turn and put it into a
variable (called "t") that can hold a TextBox ...
Unable to cast object of type 'ASP.masterpages_maindesign_master' to type
'System.Web.UI.WebControls.TextBox'.

.... but an "ASP.masterpages_maindesign_master" /isn't/ a TextBox, so
can't be held in a TextBox variable, so the program fails.

Before casting, make sure it's valid to do so, as in

For Each c As Control In Page.Controls
If TypeOf c Is TextBox Then
With DirectCast( c, TextBox )
.Text = "test"
End With
End If
Next

HTH,
Phill W.
 
Thanks Phil,

I missed out the DirectCast statement in my example. ;-)

Regards,

Cerebrus.
 
Back
Top