Home All Groups Group Topic Archive Search About

Iterate through page controls

Author
23 Apr 2006 11:19 PM
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

Author
24 Apr 2006 6:51 AM
Cerebrus
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.
Author
24 Apr 2006 11:43 AM
Phill W.
Avon wrote:

> 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.
Author
24 Apr 2006 2:16 PM
Cerebrus
Thanks Phil,

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

Regards,

Cerebrus.