1. Technology

Changing Properties "On The Fly"

Change the Z Order of Controls


Another technique that is often useful to VB programmers is to stack identically sized controls on top of each other so only the top control is visible. The order these controls are in is called the "z order" for the "z axis" in a three dimensional coordinate system. Only the front control in the stack will respond to mouse events so you can control the options are available to the user by changing the z order of the controls in the stack. For example, if you have a button that is either "On" or "Off", you can stack two buttons in the same space and then put whichever one is active at the front.

This program varies the z order of three buttons using a timer control. Whichever one is at the front will react to a mouse click and display a message.

Public Class Form1
   Private Sub Timer1_Tick( _
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles Timer1.Tick
      ' Count the buttons
      Dim btnControl As Control
      Dim btnCount As Integer = 0
      Dim btnVal As Integer
      For Each btnControl In Me.Controls
         If TypeOf btnControl Is Button Then
            btnCount += 1
         End If
      ' Initialize the random-number generator.
      ' Generate random value between 1 and number of buttons
      btnVal = CInt(Int((btnCount * Rnd()) + 1))
      Dim btnName As String = "Button" & btnVal.ToString
      btnControl = Me.Controls(btnName)
   End Sub

   Private Sub Button1_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArgs) _
      Handles Button1.Click
      Label1.Text = "Button1 was clicked"
   End Sub

   Private Sub Button2_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArgs) _
      Handles Button2.Click
      Label1.Text = "Button2 was clicked"
   End Sub

   Private Sub Button3_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArgs) _
      Handles Button3.Click
      Label1.Text = "Button3 was clicked"
   End Sub
End Class

  1. About.com
  2. Technology
  3. Visual Basic
  4. Using VB.NET
  5. Changing Properties "On The Fly"

©2014 About.com. All rights reserved.