Can't cast as a textbox (VB)

A

Alex Shirley

Hi

Sorry this is (a sort of) repost. I am trying to trim all text boxes
on my web form. I've got no problem with the trim function, I have a
problem with casting. I am told that if I want to access the Text
property, I need to have typed reference (castit to TextBox with CType
and set the value to the property). I don't exactly know how to do
this. Could somebody show me the code?

Here is what I have so far.

---------------------------------------

Dim ThisControl As System.Web.UI.Control
Dim txtControl As TextBox

For Each ThisControl In Me.Controls
If ThisControl.GetType().ToString() =
"system.Web.UI.WebControls.TextBox" Then
txtControl = CType(ThisControl, TextBox) ' am I casting this
correctly???
txtControl.Text = "I'vechanged" 'Doesn't work
End If
Next ThisControl

-----------------------------------

I tried ThisControl = CType(ThisControl, TextBox), but the properties
won't appear for thiscontrol.

Can somebody help in this casting so I can update or
get the text property here

Many thanks

Alex
 
P

Phill. W

.. . .
I need to have typed reference (cast it to TextBox with CType
and set the value to the property).

If you /know/ you've got an object that's the right "shape" for what
you want, DirectCast() should be quicker than CType(), because it
won't even try to do any conversion, something like

For Each eCtl As Control In Me.Controls
If TypeOf eCtl Is TextBox Then
Dim txtControl As TextBox _
= DirectCast(eCtl, TextBox)
txtControl.Text = "I've changed"
End If
Next

HTH,
Phill W.
 
A

Alex Shirley

Spot on the money, Phill thankyou!

'Trim all textboxes ->
Dim ThisControl As System.Web.UI.Control
For Each ThisControl In Contacts.Controls
If ThisControl.GetType().ToString() = "System.Web.UI.WebControls.TextBox" Then
Dim txtcontrol As TextBox = DirectCast(ThisControl, TextBox)
txtcontrol.Text = Trim(txtcontrol.Text)
End If
Next ThisControl

It's worth noting that "System.Web.UI.WebControls.TextBox" is case sensative.

Cheers

Alex
 

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

Top