g-spot
asked on
Creating many objects of the same type with a for loop
How do I use a For loop to declare and create a number of similar objects
In the example below I want to create 10 Person objects each with a FirstName and LastName taken from a textbox control
For i = 2 To 10
Dim Person As Person = New Person()
Dim txtLocal As TextBox
txtLocal = CType(plhOtherInsured.Find Control("t xtFirstNam e" & LTrim(Str(i))), TextBox)
If Not txtLocal Is Nothing Then
Person.FirstName = txtLocal.Text
End If
txtLocal = CType(plhOtherInsured.Find Control("t xtLastName " & LTrim(Str(i))), TextBox)
If Not txtLocal Is Nothing Then
Person.LastName= txtLocal.Text
End If
Next
In the example below I want to create 10 Person objects each with a FirstName and LastName taken from a textbox control
For i = 2 To 10
Dim Person As Person = New Person()
Dim txtLocal As TextBox
txtLocal = CType(plhOtherInsured.Find
If Not txtLocal Is Nothing Then
Person.FirstName = txtLocal.Text
End If
txtLocal = CType(plhOtherInsured.Find
If Not txtLocal Is Nothing Then
Person.LastName= txtLocal.Text
End If
Next
Just like that, if you want to keep them I would suggest adding them to an ArrayList, or similar:
Dim people As New ArrayList()
For i = 2 To 10
Dim oPerson As Person = New Person()
Dim txtLocal As TextBox
txtLocal = CType(plhOtherInsured.Find Control("t xtFirstNam e" & LTrim(Str(i))), TextBox)
If Not txtLocal Is Nothing Then
oPerson.FirstName = txtLocal.Text
End If
txtLocal = CType(plhOtherInsured.Find Control("t xtLastName " & LTrim(Str(i))), TextBox)
If Not txtLocal Is Nothing Then
oPerson.LastName= txtLocal.Text
End If
'// Add the new person to our collection
people.Add(oPerson)
Next
Hope this helps.
Dim people As New ArrayList()
For i = 2 To 10
Dim oPerson As Person = New Person()
Dim txtLocal As TextBox
txtLocal = CType(plhOtherInsured.Find
If Not txtLocal Is Nothing Then
oPerson.FirstName = txtLocal.Text
End If
txtLocal = CType(plhOtherInsured.Find
If Not txtLocal Is Nothing Then
oPerson.LastName= txtLocal.Text
End If
'// Add the new person to our collection
people.Add(oPerson)
Next
Hope this helps.
ASKER
Oh I see. I dont need to specifically name the Person objects. I can just create them and add them to the People collection.
Once they're in the People collection I'll be able to get at them by index?
Once they're in the People collection I'll be able to get at them by index?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Dim PolicyMembers As PersonCollection = New PersonCollection()
Dim Person As Person
For i = 2 To 10
Dim txtLocal As TextBox
Dim Person & i As Person = New Person
txtLocal = CType(plhOtherInsured.Find
If Not txtLocal Is Nothing Then
Person & i.FirstName = txtLocal.Text
End If
txtLocal = CType(plhOtherInsured.Find
If Not txtLocal Is Nothing Then
Person & i.LastName = txtLocal.Text
End If
PolicyMembers.Add(Person(i
Next