you can search on the form all the NumericUpDown and therefore report the value of all zero?
I would like to do something like a for loop that controls the form and see how many objects of that type are available, then if the user presses a key, all the NumericUpDown must return a value of 0 do not know if you can do this, I ask the 'help of you experts.
Dim count As Integer
count = 0
For i = 0 To Me.GroupBox1.Controls.Count - 1
Dim name As String
name = Me.GroupBox1.Controls(i).GetType().ToString()
If name.Contains("NumericUpDown") Then
count = count + 1
End If
Next
Label1.Text = count.ToString()
The form has a Controls collection. You can loop through that and check the type by calling GetType() [inherited from System.Object]. If you want to handle subtypes of NumericUpDown, you could try casting the control to NumericUpDown while catching the exception you will see if the control is not a NumericUpDown.
Your VB coding skills are probably better than mine. Been a long time since I wrote VB. Here's a rough example. I put this code in a button click event. You can pull the whole solution from my GitHub repository: https://github.com/kc1073/Samples
Dim count As Integer
count = 0
For i = 0 To Me.Controls.Count - 1
Dim name As String
name = Me.Controls(i).GetType().ToString()
If name.Contains("NumericUpDown") Then
count = count + 1
End If
Next
Label1.Text = count.ToString()
KC
Related
I am trying to create a bowling program that will display the scores given in a multi-line text box. I've manage to get the program giving an output, but when it runs it skips asking for new inputs and just gives 5 0s on seperate lines and nothing else. I'm completely lost, any help is very much appreciated
EDIT: Sorry should have changed errors to reflect the programs changes, it looks like this now. It gives 0's instead of using the value I gave it, but it does ask for each input now.
For gameNumber As Integer = 1 To 5 Step 1
lblEnterScore.Text = "Enter Score for game #" & gameNumber
Dim Testint As Integer ' define an Integer for testing
Try
Testint = CInt(txtScoreInput.Text) ' try to convert whatever they entered to Int
Catch
MessageBox.Show("Entry is not an Integer") ' If you are here then the CInt failed for some reason, send a message
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End Try
If txtScoreInput.Text.Contains(".") Then
MsgBox("Bowling Score must be a whole number.")
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End If
If txtScoreInput.Text > MAXIMUM_SCORE Or txtScoreInput.Text < MINIMUM_SCORE Then
MsgBox("Bowling Score must be between 1 and 300.")
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End If
scoreInput(gameNumber) = CInt(txtScoreInput.Text)
' and store it in the array
' and increment the gamecounter for the next time through the loop
Next
'btnEnterScore.Enabled = False
' place the good score into the multi-line textbox
txtScoreOutputs.Text = gameScore & vbCrLf & txtScoreOutputs.Text
End Sub
If it was me, here's what I would do... Just a suggestion; I also cut out over half of your code and stopped it from throwing exceptions as well... You can put this in a click event or where ever you need it as well. You can modify this as well to take as many as you want from user input as well not just limit them from entering score's. Your user also has the option to get out of that loop when they choose to do so as well, not keeping them inside the loop...
Private ScoreLists As New List(Of Integer) 'Hold your inputted values
Private Const MAXIMUM_SCORE As Integer = 300 'Max score
Private Const MINIMUM_SCORE As Integer = 1 'Min score
Private blnStop As Boolean = False
Try
For gameNumber As Integer = 1 To 5
Dim intScore As Integer = 0
Do Until (intScore >= MINIMUM_SCORE And intScore <= MAXIMUM_SCORE) OrElse blnStop
If Not Integer.TryParse(InputBox("Please enter a score for game # " & gameNumber.ToString), intScore) Then
If MsgBox("Bowling Score must be a whole number. Stop getting scores?.", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
blnStop = True
Exit For
End If
End If
Loop
ScoreLists.Add(intScore)
Next
'Display the results...
For i As Integer = 0 To ScoreLists.Count - 1
txtScoreOutputs.Text &= ScoreLists.Item(i.ToString)
Next
ScoreLists.Clear()
Catch ex As Exception
End Try
Construct your logic like this (pseudo):
Loop
{
AskUserForInput()
ProcessUserInput()
}
The loop part will control how many scores the user is prompted to enter. The AskUserForInput() function will prompt the user to type in a new score, and the ProcessUserInput() function will get the value and store it in an array or print it to the screen, etc.
Your current logic is not waiting for any new user input before trying to add to the scores. You are also getting zeros because you're setting the txtScoreOutputs with gameScore, which doesn't look like it's been set to the user's input.
I'm creating a program to calculate the average. There are 12 TextBox and I want to create the possibility to leave some fields blank. Now there are only errors and the crash of the program. Is possible to create that?
This is part of code:
ItalianoScritto = (TextBox1.Text)
MatematicaScritto = (TextBox2.Text)
IngleseScritto = (TextBox3.Text)
InformaticaScritto = (TextBox4.Text)
ScienzeScritto = (TextBox5.Text)
FisicaScritto = (TextBox6.Text)
MediaScritto = (ItalianoScritto + MatematicaScritto + IngleseScritto + InformaticaScritto + ScienzeScritto + FisicaScritto) / 6
Label10.Text = Str(MediaScritto)
If i leave blank the textbox1 when I click on the button to calculate the average Vb says Cast not valid from the string "" to type 'Single' and the bar of te textbox1 become yellow
I would do the following:
Iterate over the textboxes and check if you can parse the value into an iteger. If yes, add it to a value list.
Then add all values from that list and divide it by the number of cases.
It is faster than big if-statements and resilient against error
dim TBList as new list(of Textbox)
'add your textboxes to the list here
TbList.add(Textbox1)
...
dim ValList as new List(Of Integer)
for each elem in Tblist
dim value as integer
If integer.tryparse(elem.text,value)=True
ValList.add(Value)
else
'report error or do nothing
end if
next
dim Result as Integer
Dim MaxVal as Integer =0
for each elem in ValList
Maxval +=elem
next
Result = MaxVal / ValList.count
If you need support for point values, just choose double or single instead of Integer.
Also: regardless what you do -CHECK if the values in the textboxes are numbers or not. If you omit the tryparse, somebody will enter "A" and your app will crash and burn
Also: You OPTION STRICT ON!
You just have to check if the TextBox is blank on each one before using the value:
If TextBox7.TextLength <> 0 Then
'Use the value inside
End If
The way to do it depends a lot of your code. You should consider editing your question giving more information (and code) in order to us to help you better.
I have the following code:
For Each control2 As Control In GroupBox3.Controls
If TypeOf control2 Is TextBox Then
Dim txt2 As TextBox = TryCast(control2, TextBox)
If counter > totalBoxes Then
totalBoxes += 1
txt2.Text = grade(totalBoxes)
End If
End If
Next
What I am doing is looping through each textbox in groupbox3. Then checking if the counter(total number of grades that are inputted in the form) are greater than the totalBoxes(which is set to 0) and finally I am putting the actual grade(A,B,C,D) into the textbox. The problem is that it is starting the loop at textbox 8(I have 10 textboxes) for some reason and going from there. Does anyone know what the problem is with my code?
Aaron
Well, the name of your textbox has no relation to its index in the .Controls collection of its parent.
One thing you could do is set the .tag property of each of your controls to the index you'd like to pass into your grade function.
textbox1.Tag = 1
textbox2.Tag = 2
...
That way you don't have to worry about which order the textboxes are in while iterating.
For Each box As TextBox In GroupBox3.Controls.OfType(Of TextBox).OrderBy(Function(t) t.Name)
If counter > totalBoxes Then
totalBoxes += 1
box.Text = grade(totalBoxes)
End If
Next box
Here is my code.
for example TextBox1.Text= 12,34,45,67,67
Dim process_string As String() = TextBox1.Text.Split(New Char() {","})
Dim process As Integer
For Each process In process_string
Combo1.Items.Add(process)
count = count + 1
Next process
total_process.Text = count
End If
Dim array(count) As String
Dim a As Integer
For a = 0 To count - 1
array(a) = Combo1.Items(a).ToString
Next
a = 0
For a = count To 0
Combo2.Items.Add(array(a).ToString)
Next
i want to add values in reversed order in combobox2 that are available in combobox1
but when i run the application the second combobox remains empty and not showing any value.
You've specified this for loop
For a = count To 0
But you need to add STEP -1 to go backwards like that.
For a = count To 0 Step -1
2 things. First of all, K.I.S.S. Keep it simple stupid
For i As Integer = ComboBox1.Items.Count - 1 To 0 Step -1
ComboBox2.Items.Add(ComboBox1.Items(i))
Next
second: It didn't work because you forgot the Step -1 on your last loop
~~~~~~~~~~~~~~Edit~~~~~~~~~~~~~~
Sorting the data in a combo box should be done with the sorted property on a combo box
ComboBox3.Sorted = True
Sorting the data in reverse order should be done with arrays as you were trying to do before. The following code should suffice:
Dim List As ArrayList = ArrayList.Adapter(ComboBox3.Items)
List.Sort()
List.Reverse()
ComboBox4.Items.AddRange(List.ToArray)
If you wanted to get creative, you could potentially create your own combo box class and make your own version of the sorted property that allows for "sort alpha", "sort numeric", "sort alpha Desc", and "sort numeric desc" and perhaps some other options. But I'd only do that if you were going to use this in a lot of places.
I am using My.Settings in visual studio 2008 to store information, for when the user runs the program again.
I have that working fine... but as I am using 12 textboxes I don't want to write...
my.settings.grade1 = textbox1.text
for each one, and I am also making calculations using the stored information, so I dont want to be writing my.settings.grade1 + my.settings.grade2 etc..
Any help welcome
Thanks =)
On your form that has the textboxes, add them to a collection or an array of textboxes when the form is initialised.
Then, iterate through the collection or array of textboxes to assign to the setting value.
If you don't want to manually code the assignment of the textboxes into the array, then in your form initialisation code, iterate through all controls on the form and check for the control type or a specfici 'Tag' you assign to each textbox, then add each textbox to the array that 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 ApplicationSettings Binding to automatically bind your values to your Textboxes.Text properties. This will support 2-way binding and then all you have to do is Call Save when you close.
or you could do something like this:
given the your textboxes are named along the lines of: Grade1, Grade2, Grade3, etc.
you could store the Grades in an Array and then loop through the array:
((TextBox)form.findControl("Grade" + i.ToString())).Text = Grade(i)
Depending on your calculation, then you could also execute the calculation inside the loop.
Populate a List of grade textboxes:
'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