Visual Basic For Loop how to compare listbox to another listbox? - vb.net

So im suppose to make a program on VB that records numbers into a list box and find the average, and then i am suppose to compare the previous list box numbers and transfer any number that are above average into the other list-box.
Here is my code so far. I am stuck on the part where I have to transfer the numbers that are above average to another list box.
My logic is [show the count of the numbers, then compare the count of numbers to the average, and any numbers that are greater than the average, ill added onto the new list box] but i dont know how to write the syntax.
Option Strict On
Public Class frmAverageOfScore
Private Sub btnRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecord.Click
Dim lblscore As Double
lblscore = CDbl(txtScore.Text)
lstListofScores.Items.Add(lblscore)
End Sub
Private Sub btnAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAverage.Click
Dim listScores As Integer = lstListofScores.Items.Count
Dim sum As Double = 0
For average As Integer = 0 To (listScores - 1)
sum += CDbl(lstListofScores.Items(average))
Next
txtAverage.Text = (sum / listScores).ToString("N")
End Sub
End Class

Your existing two routines already provide the foundation for what you need to do. For example, you're already looping through the items in the first list in your averaging routine. Now, just compare each to your average, and populate the second list if they are greater, similar to how you populate the first list.
For i As Integer = 0 To (listScores - 1)
If (CDbl(lstListofScores.Items(i)) > CDbl(txtAverage.Text)) Then
lstListofScores2.Items.Add(lstListofScores.Items(i))
End If
Next
Something to note: There are far more efficient, and readable ways to do this, but I wanted to use code similar to what you've already written. You already know the functionality, you just have to apply it in a slightly different way. Some simple suggestions: store a variable for the average (probably as a Double) so you aren't recalculating it every iteration; use a For Each loop to iterate the Items in the ListBox instead of a For..Next loop, etcetera.

Related

How to set maximum of two numericupdown control

I was making a cinema booking software where after I choose the seats, it stores the number of seats I selected in an integer counter.
I have two NumericUpDown controls: nudAdult & nudKids
My problem is I have to make sure the maximum value of both NumericUpDown controls can't exceed the seatNum counter.
For eg: If the number of seats I chose is 3, both values of nudAdult & nudKids cannot exceed 3 when added together. So nudAdult can be 2 and nudKids can be 1 and I can't increase anymore than that.
I would appreciate if anyone could help me or give me some pointers to solve this problem.
Thank you for any help.
Edit: This might have been a wrong approach but it worked to an extend
Private Sub nudAdult_ValueChanged(sender As Object, e As EventArgs) Handles nudAdult.ValueChanged
totalCount = Convert.ToInt32(nudAdult.Value) + Convert.ToInt32(nudKids.Value)
Call CheckIfExceed(nudAdult)
End Sub
Private Sub nudKids_ValueChanged(sender As Object, e As EventArgs) Handles nudKids.ValueChanged
totalCount = Convert.ToInt32(nudAdult.Value) + Convert.ToInt32(nudKids.Value)
Call CheckIfExceed(nudKids)
End Sub
Private Sub CheckIfExceed(c As NumericUpDown)
Dim left As Integer
If totalCount <= seatCounter Then
left = seatCounter - totalCount
c.Maximum = totalCount + left
Else
c.Maximum = c.Value - 1
End If
End Sub
You don't have to check anything. As I said, think about a physical problem. Let's say that you have 10 balls and two bags and you can put the balls into the bags. The maximum number of balls you can put in either bag is obviously the number of balls in that bag plus the number of balls not yet in either bag. That means that, when you start and both bags are empty, then maximum for each bag is the total number of balls. BOOM! You now know that you need to set the Maximum of each NumericUpDown to the total number of seats at the start.
Now, when you place a ball in a bag, the maximum number of balls that can be placed in the other bag obviously decrements by one. BOOM! You now know that when the Value of one of your NumericUpDown controls changes, you need to change the Maximum of the other the same amount in the opposite direction.
Look at that! Problem solved with less than a minute considering an analogous physical problem.
Private total As Integer 'Set total here.
Private Sub Start()
NumericUpDown1.Maximum = total
NumericUpDown2.Maximum = total
End Sub
Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged
NumericUpDown2.Maximum = total - NumericUpDown1.Value
End Sub
Private Sub NumericUpDown2_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown2.ValueChanged
NumericUpDown1.Maximum = total - NumericUpDown2.Value
End Sub

DataGridView flickering issue [duplicate]

I am using vb.net and I have data coming into my DGV and I have a column labeled deployed if it's a '1', I want to have all the rows with '1' in the deployed column RED and if it's a '0', I want all the rows to be GREEN. This is my method I have, right now the column is the 10th column but it doesn't like the = operator. Even when I use quotes on the 1 with equals compare operator for strings. Should be an integer but I was trying every way I could to see why it's not working.
Private Sub LaptopGrid_CellFormatting(ByVal Sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles LaptopGrid.CellFormatting
For i As Integer = 0 To LaptopGrid.Rows.Count - 1
If LaptopGrid.Rows(i).Cells(9).Value = 1 Then
LaptopGrid.RowsDefaultCellStyle.BackColor = Color.Green
End If
Next
End Sub
There are a couple of issues with your code.
First, you are handling the CellFormatting event but you are iterating every row to set the backcolor. That event is meant for you to do something to a single, specific cell, the one in question is indicated in the event args: e.RowIndex and e.ColumnIndex. Using a loop, you are acting on many more rows than needed and doing so over and over.
Second, VB has data types. Int32 is one type, String is another, and Object is yet another. You need to convert one type to the other type before you compare. LaptopGrid.Rows(r).Cells(c).Value returns Object (since a cell can literally hold anything), so to compare to 1 you need to convert it to integer.
Finally, you may not want the CellFormatting event for this. If the cell in question is not on screen, the event wont fire (perhaps the user resized the columns). RowPrePaint on the other hand will fire when the row scrolls into view.
Private Sub dgv1_RowPrePaint(sender As Object,
e As DataGridViewRowPrePaintEventArgs) Handles dgv1.RowPrePaint
' dont do the NewRow
If e.RowIndex < 0 OrElse dgv1.Rows(e.RowIndex).IsNewRow Then Return
' convert to int32, then compare
' act on just this row - e.RowIndex
If Convert.ToInt32(dgv1.Rows(e.RowIndex).Cells(3).Value) > 3 Then
dgv1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LemonChiffon
Else
dgv1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.MistyRose
End If
End Sub
If the user can edit that cell value, you will want to update the back color accordingly.

Need help on generating random words for a search bot VB 2010

So i am trying to make a search bot that uses random words. I am using an increment value with Minimum of 2 and a Maximum of 30 for the number of searches to do at a time.
I was thinking something like this but it also seems like it would not be as good since it would not really generate a random string which would be a lot better:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SE As String
SE = NumericUpDown1.Value
Select Case SE
Case "2"
End Select
End Sub
If anybody could help me It would be greatly appreciated.
You can use the Random class and it's method Next to create random numbers.
Dim rnd As New Random()
Dim SE As String = rnd.Next(2, 31).ToString()
Note that the random number generation starts from a seed value. If the same
seed is used repeatedly, the same series of numbers is generated.
So if you want to use a loop, you should not create the random instance in the loop but outside of it.
However, i'm not sure what kind of words you want to create. I doubt that you want numeric strings between "2" and"30" even if your code suggests it.
Update according to your comment
The 2 and 30 are how many searches to do at a time, i want to
randomize the word(s) out of
lets say a list of 60-70 words
So i assume that you want a random number(between 2-30)of random words from a list of strings:
Dim words = {"word 1", "word 2", "word 3", ".....", "word 60"}
Dim rnd As New Random()
Dim howMany As Int32 = rnd.Next(2, 31)
Dim randomWords As New List(Of String)
For i As Int32 = 1 To howMany
Dim nextRandomIndex = rnd.Next(0, words.Count)
randomWords.Add(words(nextRandomIndex))
Next

Do until EOF loop with records in VB 2010

I have a program below that doesn't seem to be doing what I want it to do. In general, the pseudocode is: enter the number of miles (miles.text), click button, check: is the mileage entered equal to or less than the mileage radius (milestotextbox) in the database? If so, grab the truckload rate that corresponds to that radius (truckloadratetext) and display it in a textbox called "rate" (rate.text) and if not, continue looking until EOF. I've shown the code below. It lets me enter the mileage but won't check and display the result.
The data in the table looks like this:
ID MILESTO TRUCKLOADRATE
1 50 200
2 100 300
3 200 700
4 300 800
So if someone enters a mileage like 10, I want it to take the truckload rate of $200. If someone enters 250, the rate would then be 800. I'm not too hung up right now about what happens if a mileage is out of range. Just trying to figure out why the mechanics of something like this isn't working. It's my first time using records with a LOOP command so I'm trying to keep it straightforward with my program.
What could I be doing wrong? Thank you in advance and hope all has a great New Years!
Public Class Form1
Private Property EOF As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the '_test_2DataSet.test' table. You can move, or remove it, as needed.
Me.TestTableAdapter.Fill(Me._test_2DataSet.test)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Do Until EOF()
If Val(MilestoTextBox.Text) <= Val(Miles.Text) Then
rate.Text = TruckloadTextBox.Text
End If
Loop
End Sub
End Class
I neither know where you set the EOF variable nor do i understand its purpose. Have a look at following example which shows how to loop all rows of a DataTable(ORDER BY MILESTO ASC) to find the closest value greater than the given value:
Dim mileAge = Int32.Parse(Miles.Text)
Dim rate = 0
For Each row In _test_2DataSet.test
If mileAge <= row.MILESTO Then
rate = row.TRUCKLOADRATE
Exit For
End If
Next
If rate <> 0 Then
TxtRate.Text = rate.ToString
End If
If you cannot order by MILESTO initially or you simply want to see another approach that is not a database query, try this LINQ-To-DataSet approach:
rate = (From r In _test_2DataSet.test Order By r.MILESTO
Where mileAge <= r.MILESTO
Select r.TRUCKLOADRATE).FirstOrDefault
If you want to query the database, follwoing SQL returns the nearest TRUCKLOADRATE that is greater/equal than the #MileAge-parameter:
SELECT TOP (1) TRUCKLOADRATE
FROM Test
WHERE (MILESTO >= #MileAge)
ORDER BY MILESTO - #MileAge
Add a query to your DataAdapapter that returns a single value and has a meaningful name like getTruckloadRateByMileAge. Then it's that simple:
Dim loadRate = DirectCast(daTest.getTruckloadRateByMileAge(mileAge), Decimal)
Sorry for the delay in answering the question here and I want to thank everyone who answered, especially Tim.
In summary, Where a user wants to search through a dataset and compare a user-inputted value against some kind of index (in my case, if a mileage entered is less than or equal to some boundary value) and get the corresponding record that satisfies that criteria, the solution that works (thank you Tim!) is:
Dim mileAge = Int32.Parse(Miles.Text)
Dim rate = 0
For Each row In _test_2DataSet.test
If mileAge <= row.MILESTO Then
rate = row.TRUCKLOADRATE
Exit For
End If
Next
If rate <> 0 Then
TxtRate.Text = rate.ToString
End If
In the example, mileage is converted to a value that can be used to compare against a column in the dataset called MILESTO, which is a mile radius that corresponds to a price for transporting goods called TRUCKLOADRATE. The program iterates through each row in the dataset until the condition that mileage <= row.MILESTO is satisfied.
My original thought was using a search until EOF and this method works better.
Thanks all and again my apologies for the delay in summing this up for other users.

VB.net Can't get output to appear in my listbox. Beginners Question

Trying to get the user to put 3 numbers in 3 text boxes and get the average.
Private Sub btnAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAverage.Click
Dim a As Integer = CInt(txtone.Text)
Dim b As Integer = CInt(txtTwo.Text)
Dim c As Integer = CInt(txtThree.Text)
Dim average As Integer
average = (a + b + c) / 3
lstOutput.Text = average
End Sub
Try changing the type of average from Integer to Double
Dim average as Double
Right now you're trying to store the Average in an Integer which can only hold a whole number. Averages tend to be non-whole numbers and need a data type that can represent that. Double is good for most situations. That should fix your problem.
EDIT OP mentioned that lstOutput is a ListBox
This is one of the confusing things with WinForms. Even though every single control has a Text property, not all of them actually do anything. They only apply to elements that directly display a single text block or value. Ex Button, Label, etc ...
A ListBox on the other hand displays a group of items. You want to add a new item to the list.
lstOutput.Items.Add(average.ToString())
The Text property of a list box will get or set the selected item. You haven't added your average to the listbox yet.
Try:
lstOutput.Items.Add(average)
Are you sure that txtOne.text txtTwo.text and txtThree.txt will always be an integer value?
You might need to also change the a,b,c vars to Doubles and check that the user didn't supply non-numeric values.
If the user puts "one" in the txtOne textbox, you'll get an exception kablowee.
(air coding here)
dim a as new double
try
if isnumeric(txtOne.text.tostring.trim) then
a = cdbl(txtOne.text.tostring.trim)
end if
'repeat for b and c ...
catch ex as exception
messagebox.show(ex.message.tostring)
end try
And, I'm not sure if I'm right about this, (maybe someone will enlighten me) but does .NET consider type conversion from string to int differently in these two cases
a = cint(txtOne.text)
and
a = cint(txtOne.text.tostring)
???