Need help can figure out this project in VB - vb.net

This is what i have so far. cant seem to get it to work these are the guidelines
***Specifics
You will use 1 file to enter all the scores. The file is named Data.txt and should be stored in the projects Debug folder. The scores are floating point numbers.
One button should calculate the mean, range, and standard deviation and display them.
You must use separate functions to calculate the 3 statistics.
One button should display the frequencies in tabular form. For this exercise, the frequencies we are interested in are as follows:
# scores < 60
60 <= # scores < 70
70 <= # scores < 80
80 <= # scores < 90
90 <= # scores
You must use a separate array to hold the totals for the individual ranges.
All scores should be displayed in a listbox.*
Option Strict On
Public Class Form1
Private names() As String = IO.File.ReadAllLines("data.txt")
Private scores(names.Count - 1) As double
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To names.Count - 1
scores(i) = CInt(names(i))
Next
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sum As Double = 0
mean(sum)
OutputListBox.Items.Add(sum)
End Sub
Function mean(ByRef sum As Double) As Double
Dim total As Double = scores(0)
For i As Double = 0 To scores.Count - 1
sum =
Next
Return sum
End Function
End Class

I won't do all of the work for you, but here is a restructuring of your form with the mean implemented and some comments so you can figure out what is happening:
Option Strict On
Option Explicit On
Partial Public Class Form1
Private scores() As Double
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
' Clear the list view
ListView1.Clear()
' First, load the scores from the file into memory
Call LoadScores()
Dim value As Double
' Next, calculate the mean
value = CalculateMean()
' And add it to the list view
ListView1.Items.Add("Mean = " & value.ToString)
' Now calculate the other items and display them
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
''' <summary>
''' This method loads the scores from the file into the scores array
''' </summary>
''' <remarks></remarks>
Private Sub LoadScores()
Dim stringScores() As String
' Read all of the scores in the file into an array of strings
stringScores = IO.File.ReadAllLines("data.txt")
' Resize the scores array to hold all of the values in the file
ReDim scores(stringScores.Length)
Dim counter As Integer
' Now convert those strings to numbers, and store them in scores
For Each sValue As String In stringScores
' Convert the string value from the file into a double and store it in the current location in the scores array
scores(counter) = CDbl(sValue)
' Keep track of our position in the scores array
counter += 1
Next
End Sub
''' <summary>
''' The mean is the sum of the scores divided by the total number of scores
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Function CalculateMean() As Double
If scores.Length <> 0 Then
Dim total As Double
For Each value As Double In scores
total += value
Next
Return total / scores.Length
Else
' Avoid a divide by zero error
Return 0
End If
End Function
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
End Class

As with any problem, start by breaking it down and do one piece at a time. A common approach is to make one function implement one (or one part of a) requirement, so start there.
Read the file to get the scores. For this exercise, you have a hard-coded name, but it is just as easy to make the file reading function take the name as a parameter. You know the scores are listed as floating-point numbers, so you will return them as Double or Single. I see that you used an array in the code you have so far, so we'll stick with that. With that information, we can make the signature of the function
Public Function ReadScoresFromFile(fileName As String) As Double()
Calculate the mean, range, and standard deviation; three things, three functions. Based on the mathematical definitions of these three things, you will need functions that take in a sequence of numbers and will return one number. This should lead you to the function definitions:
Public Function Mean(values As Double()) As Double
Public Function Range(values As Double()) As Double
Public Function StandardDeviation(values As Double()) As Double
A quick search online or through your math/statistics book should give you definitions and formulas that you can turn into code. Hint: You may be able to call one function from one of the others to simplify the work.
Group scores into ranges. As with the file name, you have a specified list of ranges. You could try to parametrize the function to take the ranges as an argument, but its probably not worth the effort for this exercise. So, we know have a sequence of scores and need a list of total of number of scores in each range. Since totals will be integral numbers and not floating-point, we'll pick the type accordingly.
Public Function CountInRanges(scores as Double()) As Integer()
At this point, you have all the functions you need to get the data you need. Now you just have to make the various button click handlers call the appropriate functions and put the results in the appropriate labels, list boxes, etc. Use the arguments and return types to help you figure out the flow of data from one function to the next, using variables as needed to hold intermediate results.
A few things I noticed from the code you showed (none of these are required to solve your immediate problem, but could be helpful now and in the future.):
Try to give your controls meaningful names. AggregatesButton, RangesButton, MeanLabel, etc are much easier to remember than Button1, Button2, etc. (There are various styles for names as well. Some people will use a prefix instead of a suffix for names like btnAggregates, btnRanges, lblMean.)
The numeric types all have a Shared Parse method. You may consider using this instead of the conversion as it allows you to specify several options about how to parse the number from a string. For now, the conversion will probably suffice, but this is at least something to tuck away for later.
I don't know what topics your class will cover later, but you may consider looking into the For Each loop instead of the standard For loop. This can be useful when you need to do something 'for each' item in a sequence but don't care about the index, such as the Mean, Range, StandardDeviation, and CountInRanges calculations. This can make your code cleaner because you won't keep referencing the array and makes it easier to convert to other sequence classes that you may run into later (eg: List, Collection, etc). It also keeps you from accidentally modifying the array, which you never want to do in any of those functions.

Related

VB.NET tableadapter returns integer value instead of text

I'm trying to show a messagebox with the users first name from a dataset but I keep getting an integer returned.
Below is the code I'm currently using to get a 1 returned. The datatable only contains 1 column named "Name" and it is set as a system.string if that helps.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show(FirstNameTableAdapter.Fill(DsUsers.FirstNameTable, Environment.UserName), "User")
End Sub
I just feel like it's something very easy I'm missing.
The function call of FirstNameTableAdapter.Fill(DsUsers.FirstNameTable, Environment.UserName) will fill the DataTable FirstNameTable with the result of its associated CommandText. It's return value will be number of rows it has loaded.
What I think you want to be doing is calling this line separately
FirstNameTableAdapter.Fill(DsUsers.FirstNameTable, Environment.UserName)
And then calling the message box
MessageBox.Show(DsUsers.FirstNameTable.Rows(0)("Name"), "User")

vb2010 Express - Operator '=' is not defined

I'm building the retro arcade game 'Asteroids' and have been having some trouble with the collision detection of a 'shot' hitting an asteroid and splitting it into pieces.
Using the following code, I get an error in the If statement at the start of the second subroutine:
Operator '=' is not defined for types 'System.Windows.Forms.PictureBox' and 'System.Windows.Forms.PictureBox'.
Private Sub CollisionDetection_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CollisionDetection.Tick
Dim Asteroids() = {picLrgAsteroid100, picLrgAsteroid200, picLrgAsteroid300, picLrgAsteroid400, picLrgAsteroid500}
'Stores all asteroids, used for testing collision for all asteroids
For Each PictureBox In Asteroids
'For all asteroids
If PictureBox.Bounds.IntersectsWith(picBullet1.Bounds) Then
Me.Controls.Remove(picBullet1)
AsteroidDestroyer(PictureBox)
ElseIf PictureBox.Bounds.IntersectsWith(picBullet2.Bounds) Then
Me.Controls.Remove(picBullet2)
ElseIf PictureBox.Bounds.IntersectsWith(picBullet3.Bounds) Then
Me.Controls.Remove(picBullet3)
End If
'If it intersects with a bullet
'Remove the bullet, and transmit to break apart the asteroid
Next
End Sub
Public Sub AsteroidDestroyer(ByVal Asteroid As System.Windows.Forms.PictureBox)
If Asteroid = picLrgAsteroid100 Then
*
*
*
End if
As I'm using a for...each statement, how can I transmit which PictureBox is currently being run through "For each PictureBox in Asteroids", to the subroutine 'AsteroidDestroyer' and have it receive, then use it in the if statement?
Example (Pseudo-code):
sub CollisionDetection
If PictureBox (picLrgAsteroid100) intersects with picBullet1 then
Remove picBullet1
Transmit to AsteroidDestroyer(picLrgAsteroid100)
End if
End Sub
Sub AsteroidDestroyer(ByVal Asteroid as PictureBox)
If Asteroid = picLrgAsteroid100 then
End If
End Sub
And if you can see any way to improve, to avoid this problem, there's no reason I have it as I currently do, so feel free to suggest!
In lay terms, you are trying to compare two variables which contain references, and in this case, to the same object (or potentially the same object). Whereas the number one can "equal" the number one, or a variable containing the number one can "be equal to" another variable containing the number one, in contrast an object can not equal itself. Equality is a characteristic of the properties, or values of an object.
In the case of comparing references to an object vb.net provides the Is Operator. Where you might be accustomed to comparing values or properties with the equal sign,
If var1 = var2 Then
to perform a comparison of object references you would instead use ‘Is‘.
If objRef1 Is objRef2 Then
Both = and Is return a Boolean indicating a success or failure (equality/true, or inequality/false), but where the equal sign compares a value, Is compares a reference without regard to the reference's properties.
In your specific case, this translates to,
If Asteroid Is picLrgasteroid100 Then

I'm making a simple math program, however i cannot get the score to work

So far in my program, two numbers are generated and calculated by the program and saves in the AnswerTextBox.Tag. I cannot however get this score to work on screen. The validation works, just not the score counter. I mean, I've probably done the score wrong all together. Any ideas on what I can do?
Private Sub Submit_Answer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Submit_Answer.Click
Dim score As Integer = 0
ScoreTxt.Text = score
If User_Answer_Field.Text = AnswerTextBox.Tag Then
MsgBox("Well done!")
score = score + 1
Else
MsgBox("Sorry, that is false")
End If
End Sub
It looks like there are two problems here:
You output the score value before you calculate it.
You don't persist the score value anywhere, so you reset it with every answer.
The first one is easy, output it after it's been calculated:
score = score + 1
' later...
ScoreTxt.Text = score
The second one depends on a few things, such as where you want to persist this information, whether or not this is a web application, etc. At its simplest, if the instance of the form is always available and should be maintaining the score then you can simply make it a class-level member:
' class level...
Private score As Integer = 0
Private Sub Submit_Answer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Submit_Answer.Click
' don't re-create the value here
If User_Answer_Field.Text = AnswerTextBox.Tag Then
MsgBox("Well done!")
score = score + 1
Else
MsgBox("Sorry, that is false")
End If
ScoreTxt.Text = score
End Sub
So the value stays at the class level and doesn't get re-created (and, thus, reset) every time. For larger scopes you may store the value in some kind of persistence medium outside of the application, such as a database.
You are storing the score in a local variable called score. Since it's local, the variable is recreated (and initialized to zero) each time the button is clicked. Also, since the variable is local, it's value will be inaccessible from any other method. I recommend doing the following
Do some reading on variable scope
Store the score in a field of the class rather than a local variable
Don't display the value in the UI, until after it has been incremented
Every time it's clicked, score is being created, set to zero, potentially incremented, and then lost at the end of the function. Save your score variable as a member variable of the class so it's not lost.
If this isn't what you're talking about, then set a breakpoint on the If statement and find out what values are being held and compared there.
You're also comparing .Text (string) to .Tag
Make sure you're comparing the same type of variable.

my program is not adding items to listbox and is freezing up

im trying to add a very large amount of items to list box and what i need it for is i'm using to add selected items to itextsharp table report im using filters in the table just to display either the sales person who handled the customer or the date at which the incident occurred (or Issue was reported with the product) my filter system is as follows i have 4 categories which is 4 listboxes customer name, customer code(named listBox1 i have not got around to changing it yet) species name, and the error type my filter is placed under the searchBtn_Click event my filter and item adding code is as follows:
Private Sub searchBtn_Click(sender As Object, e As EventArgs) Handles searchBtn.Click
For Each obj As contactObject In custList
For Each item As speciesObject In speciesList
'loadLists()
If Trim(fromDate.Value) < Trim(obj.eventDate) Then
If Trim(toDate.Value) > Trim(obj.eventDate) Then
If Trim(fromDate.Value) < Trim(item.compDate) Then
If Trim(toDate.Value) > Trim(item.compDate) Then
End If
If Not customerListBox.Items.Contains(obj.customerName) Then
customerListBox.Items.Add(obj.customerName)
End If
If Not ListBox1.Items.Contains(obj.customer) Then
ListBox1.Items.Add(obj.customer)
End If
If Not speciesListBox.Items.Contains(item.name) Then
If ListBox1.Items.Contains(item.customerCode) Then
speciesListBox.Items.Add(Trim(item.name).ToUpper)
End If
End If
If Not errorListBox.Items.Contains(obj.issue + " - " + obj.issueDescription) Then
errorListBox.Items.Add(Trim(obj.issue + " - " + obj.issueDescription).ToUpper)
End If
End If
End If
End If
Next
Next
countErrors()
End Sub
then i have the query which is set up to get the customer info from the database system
Dim SqlText As String = "SELECT DISTINCT QEE.[EventID] ,QEE.[EventDate] ,QEE.[Employee] ,QEE.[Communication] ,QEE.[OtherCommunication] ,QEE.[Issue] ,QEE.[IssueDescription] ,QEE.[IssueComments] ,QEE.[Resolution] ,QEE.[ResolutionComments] ,QEE.[SalesOrderNumber] ,QEE.[CustomerPO] ,QEE.[SOStatus] ,QEE.[Customer] ,QEE.[CustomerName] ,QEE.[SalesPersonName] ,QEE.[IsResolved] ,QEE.[IssueValue] ,QEE.[DateAndTimeAdded] ,DATEDIFF(day, SOR.ReqShipDate, QEE.[EventDate]) AS Elapsed, SOR.ReqShipDate FROM [QualityTracking].[dbo].[tblQualityEventEntry] QEE INNER JOIN SysproCompanyC.dbo.SorMaster SOR ON QEE.SalesOrderNumber = SOR.SalesOrder COLLATE Latin1_General_CI_AS ORDER BY EventDate ASC, CustomerName ASC, SalesOrderNumber ASC;"
I could not fit all code on here
if you could also just general things to help as well i am new to vb.net but for other information things i have tried :
*listbox.startUpdate/endUpdate
*changing querys
*changing the sorted property (Right now its set for false)
*the issue happens when i choose select all and then hit search the database is holding almost 2Mil items and i need to be able to get it to move once i get it work stop freezing i will be able to increase the speed i just cant figure out totally where the issue is i know the query could be better probably (if you have any suggestions please feel free i'm learning)
*but i also see alot of people having this issue with listbox as being kinda a broken down way of listing items
*i have tried researching it and people have said use something else i cant do that for listbox is committed
Assuming Windows Forms.
You program might not be responding because of too many records to add, and each time you add an item into the ListBox.Items collection, the UI is refreshed.
You may either SuspendLayout while adding the lines into your Listbox, and ResumeLayout afterwards.
Private Sub searchBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
customerListBox.SuspendLayout();
// Place your code to populate the ListBox control here...
customerListBox.ResumeLayout();
End sub
This shall avoid a lot of refreshes from occuring while adding the items one by one and allow the application to lighten the add of items, then you resume the layout so that it refreshes the controls to display adequate information to the screen.
OR
You may use the ListBox.Items.AddRange() method along with List.ToArray().
Private Sub searchBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim custList As List(Of ConstactObject) = loadYourCustomers();
customerListBox.Items.AddRange(custList.ToArray());
Dim speciesList As List(Of SpeciesObject) = loadYourSpecies();
speciesListBox.Items.AddRange(speciesList.ToArray());
End sub
OR ELSE
I recommend using a DataGridView and setting its DataSource property to your list of objects.
So, in order to have the correct data, you'll have to:
Drop two DataGridView on your Form
Rename both DataGridView to a meaningful name (e.g. custListDataGridView, speciesListDataGridview)
Drop two BindingSource on your Form
Rename both BindingSource to a meaningful name (e.g. custListBindingSource, speciesListBindingSource)
In the designer, set the DataGridView.DataSource property to your respective BindingSource (e.g. custListDataGridview.DataSource = custListBindingsource, speciesListDataGridView.DataSource = speciesListBindingSource)
In the backing code, that is, in your searchBtn.Click event, you may set both your binding sources DataSource property
Private Sub searchBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim custList As IList(Of ContactObject) = loadYourContactObjects();
custListBindingSource.DataSource = custList;
Dim speciesList As IList(Of SpeciesObject) = loadYourSpeciesObject();
speciesListBindingSource.DataSource = speciesList;
End Sub
And your information data should be listed automatically without you having to manually add each record.

Adding a default number of items to list box in Visual Basic

I'm working on a project for my Visual Basic class and need a nudge in the right direction. I'm not going to go into exactly what the program is supposed to do in the end because I'm not really at that point yet. The step I'm stuck on now is this.
We are supposed to have two list boxes, one for Ingredients (which I've named lstIngredients) and the second for the Recipe (lstRecipe), we are also supposed to have a text box labeled Quantity for the user to enter how many of the selected item to add to the Recipe list. For example, if the user selects "eggs" and types 3 for the quantity, "eggs" should appear 3 times in the Recipe list box. Also, if nothing is put into the quantity box, it is supposed to default to adding one of the selected item to the Recipe list box.
With the code I have written, I am able to add items to the Recipe list as long as I type something into the quantity text box, but I cannot get the program to just add one when nothing is typed into the text box. Here is the code I have so far.
Public Class Form1
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim i As Integer = lstIngredients.SelectedIndex
If txtQuantity.text= "" Then
lstRecipe.Items.Add(1)
End If
Dim intCount As Integer = 0
While intCount < txtQuantity.Text
lstRecipe.Items.Add(lstIngredients.Items(i))
intCount += 1
End While
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lstRecipe.Items.Clear()
txtQuantity.Clear()
End Sub
Any help on this step would be greatly appreciated. I'm sure I'll probably have more questions as I get farther into the coding, but I will edit this question to include those when the time comes.
First, you'll need to convert the value in your Quantity text box to an integer. For that, you can use either Integer.Parse or Integer.TryParse. For instance:
Dim value As Integer = Integer.Parse(Quantity.Text)
Then you can use a For loop to add the same item that many times, for instance:
For x As Integer = 1 to value
lstRecipe.Items.Add(lstIngredients.Items(i))
Next