VB.NET ..... Help in a loop
I am using My.Settings in visual studio 2008 to store information when the user starts the program again.
It works fine for me ... but since I am using 12 text fields I don't want to write ...
my.settings.grade1 = textbox1.text
for each one and I also do calculations using the stored information, so I don't want to write my.settings.grade1 + my.settings.grade2 etc.
Any help is appreciated
Thank you =)
In your form containing text fields, add them to the collection or array of text fields when you initialize the form.
Then, iterate through the set or array of text boxes to assign a parameter value.
If you don't want to manually code the assignment of the text boxes in an array, then in your form source code, iterate over all the controls on the form and check the control type or specfici 'Tag' that you assign each text block, then add each text block to array in this way.
For Each c as Control in Me.Controls
If c.Tag.ToString() = "Grade" Then
' Add Items to collection here '
End If
Next c
Have you considered using the ApplicationSettings binding to automatically bind values ββto Textboxes.Text properties. This will support two way binding and then all you have to do is Save Call when you close.
or you can do something like this:
given your textboxes are named on strings: Grade1, Grade2, Grade3, etc.
you can store the classes in an array and then loop through the array:
((TextBox)form.findControl("Grade" + i.ToString())).Text = Grade(i)
Depending on your calculation, you can also perform calculations inside the loop.
Complete the list of class text fields:
'at the class level'
Public GradeBoxes(11) As TextBox
Const grade As String = "GRADE"
'when the form is created'
Dim i As Integer = 0
For Each ctr As Control In Controls
If TypeOf (ctr) Is TextBox AndAlso ctr.Name.ToUpper.StartsWith(grade) Then
i = CInt(ctr.Name.SubString(grade.Length))
If i >= 0 AndAlso i < GradeBoxes.Length Then GradeBoxes(i) = ctrl
End If
Next ctr
For Each box As TextBox in GradeBoxes
If box IsNot Nothing AndAlso My.Settings(box.Name) IsNot Nothing Then
box.Text = My.Settings(box.Name)
End If
Next box
Save grades:
For Each box As TextBox in GradeBoxes
If box IsNot Nothing AndAlso My.Settings(box.Name) IsNot Nothing Then
My.Settings(box.Name) = box.Text
End If
Next box
My.Settings.Save()
Do you mean something like?
Dim sum As Long
Dim grades(11) As Long
Dim i As Integer = 0
For Each ctr In Controls
If TypeOf (ctr) Is TextBox Then
grades(i) = CLng(ctr.Text)
sum = sum + grades(i)
i = i + 1
End If
Next