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

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)
???

Related

How to sum variables in VBA to check input data is correct?

May seem like a stupid question, but how do you sum variables in VBA to check input data is correct?
I'm trying to check the user has inputted data correctly into a UserForm before they continue to the next page. To do this I want to sum some of their input variables. If they don't input it correctly, they get a message box telling them to revise the numbers. My code is:
Dim BinQnt As Double
Dim FillQnt As Double
Dim FineQnt As Double
Dim CoarQnt As Double
Dim RAPQnt As Double
Dim CRQnt As Double
If BinQnt + FillQnt + FineQnt + CoarQnt + RAPQnt + CRQnt = 100 Then
'Code here for inserting values into database. Omitted to save space and confusion.
Else
MsgBox "Error, please check mixture design sums to 100%."
End If
When I'm testing it, it always goes to the error message box and I'm not sure why. Very sure I am adding variables which sum to 100 (haha). I first tried it without defining the variables, and now I have it still doesn't work.
Am I missing something obvious?
Do you want to round it or not?
In your question, you have the variables as Doubles, and in the answer as integers. Having them as integers will make it easier to hit 100%, but it will round to the nearest integer (2,4 = 2 | 2,6 = 3)
I will assume you are using all texboxes in the form, and as such use this code that is universal:
Dim tot As Double
tot = 0
For Each c In Me.Controls
If TypeName(c) = "TextBox" And IsNumeric(c.Value) Then
tot = tot + c.Value
End If
Next c
If tot = 100 Then
'Code here for inserting values into database. Omitted to save space and confusion.
Else
MsgBox "Error, please check mixture design sums to 100%. Currently at " & tot & "%."
End If
This would give us something like this:
However, using Integer or Long, gives us this:
Also, the reason as to why I'm using IsNumeric(c.Value), is to stop the code from failing in case of empty boxes (or filled with invalid entries).
You could also place a check here in case no boxes are allowed to be empty.

Visual Basic For Loop how to compare listbox to another listbox?

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.

Multiplying multiple texboxes

I am creating a menu application, I have at the moment 3 textboxes, textbox1 is price, textbox2 is quantity and textbox3 is total. I have successfully written the code to calculate the price of an item depending on the quantity they need. The code i have right now:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
TextBox8.Text = CStr(Val(TextBox6.Text) * Val(TextBox7.Text))
End Sub
Now what I need is that I will have more items say 10 along with textboxes beside as quantity which makes 20 textboxes and one total textbox. How can I write the code so that it calculates every textbox as well as null values say if out of the 10 items i want only 2 items 1 per quantity into the total value.
Thanks
First, i strongly suggest to use .NET methods instead of old VB methods. I also would set OPTION STRICT to On in general which avoids "magical" conversions done for you by the runtime. Instead you have to specify the correct types which is a good thing since it can prevent errors on runtime and it also helps to learn the .NET types and methods.
I would add those TextBoxes all to the same container-control (like a Panel or something similar). I also suggest to use more meaningful names for your controls(f.e. TxtTotal for the total-textbox).
So if all price-textboxes' names start with TxtPrice (f.e. TxtPrice1 etc) and all quantity-TextBoxes start with TxtQuantity (f.e. TxtQuantity1 etc), this LINQ query approach will work:
Dim allTextBoxes = PriceQuantityPanel.Controls.OfType(Of TextBox)()
Dim allPrices = From txt In allTextBoxes
Where txt.Name.StartsWith("TxtPrice")
Dim allQuantities = From txt In allTextBoxes
Where txt.Name.StartsWith("TxtQuantity")
Dim price As Decimal
Dim invalidPrices = From txt In allPrices
Where Not Decimal.TryParse(txt.Text, price)
If invalidPrices.Any() Then
MessageBox.Show("Please enter valid prices(Decimal)!")
Return
End If
Dim quantity As Int32
Dim invalidQuantities = From txt In allQuantities
Where Not Int32.TryParse(txt.Text, quantity)
If invalidQuantities.Any() Then
MessageBox.Show("Please enter valid quantities(Integer)!")
Return
End If
Now you can "join" the pairs of price and quantity textboxes by the number-suffix:
Dim query = From txtP In allPrices
Join txtQ In allQuantities
On txtP.Name.Substring("TxtPrice".Length) Equals txtQ.Name.Substring("TxtQuantity".Length)
Select New With {.Price = Decimal.Parse(txtP.Text), .Quantity = Int32.Parse(txtQ.Text)}
Dim totalSum As Decimal = query.Sum(Function(x) x.Price * x.Quantity)
TxtTotal.Text = totalSum.ToString()

Search Listbox and return specific number of items defined in another field - VB.net

I'm running a search query that pulls the search string from one text box, then searches a listbox for the string and displays the results in a second listbox. I would like to define the number of items that it returns based on a second text box. So far I am able to get all list items with be given string to show in the second box. But I have yet to get it to limit the search to 1 item etc. The functional code I've used to show all results is:
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
lstResults.Items.Clear()
If txtSearch.Text.Length > 0 Then
For index As Integer = 0 To lstCountries.Items.Count - 1
Dim txt = lstCountries.Items(index).ToString()
If txt.StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
lstResults.Items.Add(txt)
End If
Next
End If
I've tried using while txtnumber.text > 1 then ahead of this but seem to have created a loop. Any ideas as to what I'm missing?
The datasource is going to have the final say on how many results there are. If the user specifies 3 and there are only 2 in the source, thats all you will get. Something like this will move the results from one to the other until the max is found:
Dim Max as integer = Convert.Toint32(txtNumber.Text)
Dim Count as integer = 0
lstResults.Items.Clear()
For index As Integer = 0 To lstCountries.Items.Count - 1
if lstCountries.Items(index).StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
lstResults.Items.Add(lstCountries.Items(index))
count += 1
end if
' exit the loop if we found enough
If count>= Max Then
Exit For
End If
Next
If the listbox just contains text (strings) then you do not need the ToString: lstCountries.Items(index).StartsWith(strSearch). Basically, you need to exit the loop once the user desired number have been found OR if you run out of data...if I understood right. while txtnumber.text > 1 would not work because textboxes contain strings not numerics (23 is not the same as "23").
The LINQ extensions would work well here as well:
lstResults.Items.AddRange((From item In lstCountries.Items
Let strItem As String = item.ToString
Where strItem.StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase)
Select strItem).Take(Integer.Parse(txtnumber.Text)).ToArray)
This assumes that all your data has already been validated.

Use formula for multiplication?

I have two fields on a record ("Qty" and "Harga").
How do I multiply the two and save result into another field in a ListView?
The ListView control has no built-in ability to perform calculations for you, like a spreadsheet. It just displays whatever data you give it to display. If you want it to display the product of a multiplication equation, you will need to do that calculation yourself in the code and then add the result to the ListView column. For instance:
Public Sub AddItem(description As String, total As Integer, count As Integer)
Dim i As ListViewItem = ListView1.Items.Add(description)
i.SubItems.Add(total.ToString())
i.SubItems.Add(count.ToString())
Dim product As Integer = total * count
i.SubItems.Add(product.ToString())
End Sub