How to pass controls to subs?

  • Thread starter Thread starter Terry Olsen
  • Start date Start date
T

Terry Olsen

I'd like to change the background color of each textbox on my form to a
different color when entered. The code below doesn't work (invalid cast
error) but you should be able to get the gist of what I want to do. Any
help is appreciated. Thanks.

Private Sub txtHubMnemonic_Enter(ByVal sender As Object, ByVal e As
System.EventArgs) Handles txtHubMnemonic.Enter
'SetBackColor(sender)
SetBackColor(txtHubMnemonic)
End Sub

Private Sub SetBackColor(ByRef MyTB As TextBox)
For Each TB As TextBox In Me.Controls
TB.BackColor = System.Drawing.Color.White
Next
MyTB.BackColor = System.Drawing.Color.BlanchedAlmond
End Sub
 
Terry Olsen said:
I'd like to change the background color of each textbox on my form to a
different color when entered. The code below doesn't work (invalid cast
error) but you should be able to get the gist of what I want to do.
[...]
Private Sub txtHubMnemonic_Enter(ByVal sender As Object, ByVal e As
System.EventArgs) Handles txtHubMnemonic.Enter
'SetBackColor(sender)
SetBackColor(txtHubMnemonic)

=> 'SetBackColor(DirectCast(sender, TextBox))'.
Private Sub SetBackColor(ByRef MyTB As TextBox)

'ByRef' => 'ByVal'
For Each TB As TextBox In Me.Controls

\\\
For Each ctr As Control In Me.Controls
If TypeOf ctr Is TextBox Then
DirectCast(ctr, TextBox).<...> = ...
...
....
///
 
Thanks! That worked... Of cource I had to nest the For...Each due to each
of my text boxes being in its own GroupBox... But I got it dun!

Herfried K. Wagner said:
Terry Olsen said:
I'd like to change the background color of each textbox on my form to a
different color when entered. The code below doesn't work (invalid cast
error) but you should be able to get the gist of what I want to do.
[...]
Private Sub txtHubMnemonic_Enter(ByVal sender As Object, ByVal e As
System.EventArgs) Handles txtHubMnemonic.Enter
'SetBackColor(sender)
SetBackColor(txtHubMnemonic)

=> 'SetBackColor(DirectCast(sender, TextBox))'.
Private Sub SetBackColor(ByRef MyTB As TextBox)

'ByRef' => 'ByVal'
For Each TB As TextBox In Me.Controls

\\\
For Each ctr As Control In Me.Controls
If TypeOf ctr Is TextBox Then
DirectCast(ctr, TextBox).<...> = ...
...
...
///
 
Terry Olsen said:
Of cource I had to nest the For...Each due to each of my text boxes being
in its own GroupBox...

Alternatively you can use a more flexible recursive function for control
enumeration:

\\\
Private Sub RecurseControls(ByVal ctr As Control)
Debug.WriteLine(ctr.Name)
If ctr.HasChildren Then
For Each c As Control In ctr.Controls
RecurseControls(c)
Next c
End If
End Sub
..
..
..
RecurseControls(Me)
///
 

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