18.01.2013 Views

Mastering Visual Basic .NET

Mastering Visual Basic .NET

Mastering Visual Basic .NET

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

236<br />

Chapter 5 WORKING WITH FORMS<br />

The control you see at the top of the form is the NumericUpDown control. All you really need<br />

to know about this control is that it fires the ValueChanged event every time the user clicks one of<br />

the two arrows or types another value in its edit area. This event handler’s code adds or removes<br />

controls on the form, so that the number of TextBoxes (as well as the number of the corresponding<br />

labels) matches the value on the control. Listing 5.15 shows the handler for the ValueChanged event<br />

of the NumericUpDown1 control. The ValueChanged event is fired when the user clicks one of the<br />

two arrows on the control or types a new value in the control’s edit area.<br />

Listing 5.15: Adding and Removing Controls at Runtime<br />

Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, _<br />

ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged<br />

Dim TB As New TextBox()<br />

Dim LBL As New Label()<br />

Dim i, TBoxes As Integer<br />

‘ Count all TextBox controls on the form<br />

For i = 0 To Me.Controls.Count - 1<br />

If Me.Controls(i).GetType Is GetType(System.Windows.Forms.TextBox) Then<br />

TBoxes = TBoxes + 1<br />

End If<br />

Next<br />

‘ Add new controls if number of controls on the form is less<br />

‘ than the number specified with the NumericUpDown control<br />

If TBoxes < NumericUpDown1.Value Then<br />

TB.Left = 100<br />

TB.Width = 120<br />

TB.Text = “”<br />

For i = TBoxes To NumericUpDown1.Value - 1<br />

TB = New TextBox()<br />

LBL = New Label()<br />

If NumericUpDown1.Value = 1 Then<br />

TB.Top = 20<br />

Else<br />

TB.Top = Me.Controls(Me.Controls.Count - 2).Top + 25<br />

End If<br />

Me.Controls.Add(TB)<br />

LBL.Left = 20<br />

LBL.Width = 80<br />

LBL.Text = “Data Point “ & i<br />

LBL.Top = TB.Top + 3<br />

TB.Left = 100<br />

TB.Width = 120<br />

TB.Text = “”<br />

Me.Controls.Add(LBL)<br />

AddHandler TB.Enter, _<br />

New System.EventHandler(AddressOf TBox_Enter)<br />

AddHandler TB.Leave, _<br />

New System.EventHandler(AddressOf TBox_Leave)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!