|
-
Mar 9th, 2005, 06:35 AM
#1
Thread Starter
PowerPoster
Control Arrays
Hi,
A common misconception is that Control Arrays have disappeared from VB.NET. They haven't. What has disappeared is the Index Property of a control and the ability to create the array automatically in design view.
MSDN Help will give several work-arounds, including use of the Tag property but the simplest way is to use an Array of Controls. The following creates ten textboxes in code and stores a reference to each one in an array.
VB Code:
Dim arrTextBox(0) As TextBox ' (Prepare array to receive textBoxes.
' Give this the necesary scope)
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim txtTemp As TextBox ' ( Reserve variable for new textbox
' Local scope only OK)
Dim iCount As Integer (Local scope only)
For iCount = 0 To 9
ReDim Preserve arrTextBox(iCount) '(Expand array to receive
' next textbox
txtTemp = New TextBox ' ( Create instance of new textbox)
txtTemp.Name = "txtBox" & iCount.ToString '(Name textboxes with
'sequential numbering)
txtTemp.Width = 40
txtTemp.Location = New Point(15, iCount * 20)
Me.Controls.Add(txtTemp) '(Add new textbox to form
arrTextBox(iCount) = txtTemp '(Place reference to new textbox
'in appropriate element of array)
'(The next line adds the handle of the new textbox to the appropriate event)
AddHandler txtTemp.TextChanged, AddressOf TextChangedEvent
Next
End Sub
Private Sub TextChangedEvent(ByVal sender As System.Object, ByVal e As System.EventArgs)
MessageBox.Show(CType(sender, TextBox).Name & " Text was changed")
End Sub
You can now refer to each TextBox by the array subscript ( index no.)
This is better than the VB6 Control Array because you can mix any type of object by replacing
Dim txtTemp As TextBox
Dim arrTextBox() As TextBox
txtTemp = New TextBox
with
Dim txtTemp As Object
Dim arrTextBox() As Object
txtTemp = New Object
You could then widen the possibilities by using a 2 dimension array, allocating the elements of the first dimension to hold different types or groups of objects, although those elements would only hold numeric values of course.
EDIT; Handler for Text_Changed event added, see Wossname's comment.
Last edited by taxes; Mar 11th, 2005 at 06:02 AM.
Taxes
The more I learn about VB.NET the more I like dBaseIII Plus
The foregoing, whilst believed to be correct, is given without guarantee as to it's accuracy and entirely without recourse. You are required to decide for yourself whether or not it is suitable for your purposes and no liability for loss of any nature can be entertained.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|