Food Survey Application - vb.net

Okay so this code is a list of items in a combobox and you have to pick one item and then choose a radiobutton like or dislike and then hit vote.The results list box should total up all the votes every time you click like or dislike and hit vote. When I click like and press vote nothing shows up in the results box but when I hit dislike and press vote it shows up and the total is correct for the like I pressed and hit vote so it shows 1 for each. It stays that way the whole time while the program is running, so if I hit like 3 more times it won't update in list box until I hit dislike and press vote. How do I code to show up and update on both like and dislike votes?
Here is my code:
Public Class FoodSurveyForm
Dim votes As Integer(,) = New Integer(0 To 3, 0 To 1) {}
' handles Food Survey Form's Load event
Private Sub FoodSurveyForm_Load(sender As System.Object,
e As System.EventArgs) Handles MyBase.Load
foodsComboBox.SelectedIndex = 0 ' select first food in list
End Sub ' FoodSurveyForm_Load
Private Sub voteButton_Click(sender As System.Object, e As System.EventArgs) Handles voteButton.Click
Dim index As Integer = foodsComboBox.SelectedIndex
'if statement to add like and dislike votes
If likeRadioButton.Checked Then
votes(index, 0) += 1
ElseIf dislikeRadioButton.Checked Then
votes(index, 1) += 1
DisplayVotes()
End If
End Sub
Sub DisplayVotes() 'call DisplayVotes sub procedure
resultsListBox.Items.Clear()
'header for resultListBox
resultsListBox.Items.Add("Menu Item" & ControlChars.Tab & "Like" _
& ControlChars.Tab & "Dislike")
For count As Integer = 0 To foodsComboBox.Items.Count - 1
resultsListBox.Items.Add(foodsComboBox.Items(count).ToString & ControlChars.Tab & votes(count, 0) & _
ControlChars.Tab & votes(count, 1))
Next count
End Sub ' Display Votes
End Class ' FoodSurveyForm

DisplayVotes() must go outside of the if block:
Private Sub voteButton_Click(sender As System.Object, e As System.EventArgs) Handles voteButton.Click
Dim index As Integer = foodsComboBox.SelectedIndex
'if statement to add like and dislike votes
If likeRadioButton.Checked Then
votes(index, 0) += 1
ElseIf dislikeRadioButton.Checked Then
votes(index, 1) += 1
End If
DisplayVotes()
End Sub

Related

Calculate cost of several items with tax and a discount

Can anyone help with this school task I have
The task is to ask the user for items and the cost of the items until they chose to stop. Then combine all the costs and take 20% VAT and 10% off from 2 randomly selected items.
Here is the code I have so far (I have 2 buttons and a listbox)
Public Class Form1
Dim CurrentA As Integer
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim Items(CurrentA) As String
Dim Coins(CurrentA) As Single
Dim Stay As String
CurrentA = 0
Do Until CurrentA = 20
Items(CurrentA) = InputBox("Please Enter The Item")
Coins(CurrentA) = InputBox("Please Enter The Cost Of The Item")
Stay = InputBox("Type Yes If More Items or Type No if no More")
Stay = Stay.ToLower
If Stay = "yes" Then
End If
If Stay = "no" Then
Exit Do
End If
ListBox1.Items.Add(Items(CurrentA) & " " & Coins(CurrentA))
CurrentA += 1
Loop
End Sub
End Class
First, a few comments on the code you presented.
Dim CurrentA As Integer
'An Integers default value is zero, I don't see why this is a class level variable
'always declare variables with as narrow a scope as possible
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Items(CurrentA) As String 'Declares an Array of Type String with an Upper Bound of 0
'Upper Bound is the highest index in the array
'Arrays start with index 0
'So your array will have 1 element at index 0
Dim Coins(CurrentA) As Single
Dim Stay As String
CurrentA = 0 'unnecessary because the default of CurrentA is already 0, but OK for clarity because it could have been changed elsewhere
'This is behaving like a console application with the code repeating in a loop.
'In Windows Forms it would be more likely to do this in a button click event (btnAddItem)
Do Until CurrentA = 20
'On the first iteration CurrentA = 0
'On the second iteration CurrentA = 1 - this exceeds the size of your array
'and will cause an index out of range error
Items(CurrentA) = InputBox("Please Enter The Item")
'With Option Strict on you must change the input to a Single
Coins(CurrentA) = CSng(InputBox("Please Enter The Cost Of The Item"))
Stay = InputBox("Type Yes If More Items or Type No if no More")
Stay = Stay.ToLower 'Good! The user might no follow directions exactly
If Stay = "yes" Then
'This is kind of silly because it does nothing
End If
'Lets say I say no on the first iteration
'This avoids the index out of range error but
'nothing is added to the list because you Exit the loop
'before adding the item to the ListBox
If Stay = "no" Then
Exit Do
End If
ListBox2.Items.Add(Items(CurrentA) & " " & Coins(CurrentA))
CurrentA += 1
Loop
End Sub
We could use arrays but not knowing how many items will be added means either making the array bigger than needed or using Redim Preserve on every addition. A much better choice is a List(Of T). They work a bit like arrays but we can just add items without the ReDim stuff.
Private lstCost As New List(Of Single)
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'Pretend this button is called btnAdd, and you have 2 test boxes
lstCost.Add(CSng(TextBox2.Text))
'The $ introduces an interpolated string. It is a step up form String.Format
ListBox2.Items.Add($"{TextBox1.Text} - {CSng(TextBox2.Text):C}") 'The C stands for currency
TextBox1.Clear()
TextBox2.Clear()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Pretend this button is called btnTotal
'Dim total As Single = (From cost In lstCost
' Select cost).Sum
Dim total As Single = lstCost.Sum
Label1.Text = total.ToString("C") 'C for Currency
End Sub

Can't reconcile votes with candidates

Good morning all,
I'm working on a voting program in Visual Basic (using Visual Studio 2013 if that makes any difference), and I can't seem to get the votes per candidate to function.
This is an assignment so I must use the listbox.DoubleClick event handler for the selected index to tally the votes.
Thus far I have written the entire program to my liking but I cannot get the votes to coincide with the candidates. I think it has to do with this block of code
Try
'Selected candidate gets a vote tallied
vote(candidateList.SelectedIndex) += 1
candidateList.SelectedIndex = -1
Catch exc As IndexOutOfRangeException
MessageBox.Show("Please click on a candidate to vote.", "Attention!")
End Try
My entire project can be seen here if needed - Voting Machine source code
Any idea what will help my program reconcile the data? Or what my error is?
Thank you!
Edit- I've gotten it mostly working now, I get an accurate number of votes per candidate, but now I need to figure out how to get both the candidate name and their total votes in the same listbox.
The above code displays the correct votes in the correct order, but if I try to add the candidateList.selectedItem into the mix it throws an invalid cast exception as the string (candidates name) cannot be converted to an integer. How do I get the selectedItem and increment the count for the selected index? I'm stuck at this point now for most of today and help would be greatly appreciated.
Thank you!
I took a look at your code. You need to initialize the "vote" array before you start using it. You have this line:
Dim vote() As Integer
Which doesn't actually initializes the array of integers. Here are some examples how you could initialize is with a length of 3 or 3 variables.
Dim vote(3) As Integer
Dim vote As Integer() = {1,2,3}
By the way, it would also be best to check that "candidateList.SelectedIndex" has an actual valid value (isn't -1).
In your code, the vote array is declared but not initialized which is causing the NullReferenceException
Please initialize the array with proper dimension, For instance you can do that in your code in "showCandidates()" function as follows,
Sub showCandidates()
'Display the candidates in the listbox and sort alphabetically by last name
Dim query = From candidate In Candidates
Let firstName = candidate.Split(" "c)(0)
Let lastName = candidate.Split(" "c)(1)
Let name = firstName & " " & lastName
Order By lastName
Select name
For Each Name As String In query
candidateList.Items.Add(Name)
Next
'Initialize the vote array.
ReDim Preserve vote(candidateList.Items.Count)
End Sub
ReDim the vote array whenever you are adding a candidate to the list box (i-e nominate candidate) otherwise you may get an IndexOutOfBounds Exception.
I figured out the solution to my problem. Many thanks to those that helped me!
Imports System.IO
Public Class Voting
Dim Candidates() As String
Dim votes() As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Get default values and views for Voting Machine
resultsList.Visible = False
candidateList.Location = New Point(143, 71)
tallyVotes.Enabled = False
resultsList.Enabled = False
Label1.Text = "Click 'Nominate Candidate' to enter a candidate, or 'Start Voting'" & vbCrLf & "to end nominations and start the voting."
End Sub
Private Sub candidateList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles candidateList.SelectedIndexChanged
End Sub
Private Sub resultsList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles resultsList.SelectedIndexChanged
End Sub
Private Sub nominateCandidate_Click(sender As Object, e As EventArgs) Handles nominateCandidate.Click
'Instructions
MessageBox.Show("When finished entering candidates, simply press enter on a blank line.", "Instructions")
'Gather list of Candidates
Dim candidateName = InputBox("Enter the name of your candidate (first and last name please):", "Candidate Name", "", 500, 500)
Dim i As Integer = 0
'Loops until a null string is entered signaling the end of input
Do Until String.IsNullOrEmpty(candidateName)
ReDim Preserve Candidates(i)
Candidates(i) = candidateName
i += 1
candidateName = InputBox("Enter the name of your candidate (first and last name please):", "Candidate Name", "", 500, 500)
Loop
End Sub
Private Sub startVoting_Click(sender As Object, e As EventArgs) Handles startVoting.Click
'Disable the Nomination button
nominateCandidate.Enabled = False
'Enable the tally votes button
tallyVotes.Enabled = True
'Set the label text to give instructions for tallying votes.
Label1.Text = "Vote for a candidate by double-clicking his or her name." & vbCrLf & "End the voting by clicking on 'Tally Votes'."
'Call sub to display the candidates for voting
showCandidates()
End Sub
Private Sub tallyVotes_Click(sender As Object, e As EventArgs) Handles tallyVotes.Click
'Makes results listbox visible and moves the candidate list to the left
resultsList.Visible = True
candidateList.Location = New Point(14, 71)
'Call the sub to tally the votes and display the winner
getResults()
End Sub
Private Sub candidateList_DoubleClick(sender As Object, e As EventArgs) Handles candidateList.DoubleClick
'Selected candidate gets a vote tallied
Try
'Selected candidate gets a vote tallied
votes(candidateList.SelectedIndex) += 1
candidateList.SelectedIndex = -1
Catch exc As IndexOutOfRangeException
MessageBox.Show("Please click on a candidate to vote.", "Attention!")
End Try
End Sub
Sub showCandidates()
'Display the candidates in the listbox and sort alphabetically by last name
Dim query = From candidate In Candidates
Let firstName = candidate.Split(" "c)(0)
Let lastName = candidate.Split(" "c)(1)
Let name = firstName & " " & lastName
Order By lastName
Select name
For Each Name As String In query
candidateList.Items.Add(Name)
Next
ReDim Preserve votes(candidateList.Items.Count - 1)
End Sub
Sub getResults()
'Add the results to the Results Listbox
For Each i In votes
resultsList.Items.Add(i)
Next
'Declare Winner
Dim mostVotes As Integer = 0
For Each item In resultsList.Items
If item > mostVotes Then
mostVotes = item
End If
Next
resultsList.SelectedItem = mostVotes
candidateList.SelectedIndex = resultsList.SelectedIndex
Dim winner = candidateList.SelectedItem
MessageBox.Show("The winner is " & winner)
End Sub
End Class

Combo Box Returning -1 For SelectedIndex

I'm trying to pick up a combo box's selected index. This was working absolutely fine, then all of a sudden it started returning -1 no matter what item is selected
My code is:
Form Code
Private Sub Man_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Man.SelectedIndexChanged, Units.SelectedIndexChanged
'Set Transducer Type
Call References.LevListAdd()
End Sub
References Module LevListAdd Sub
Public Sub LevListAdd()
Form1.Lev.Items.Clear()
If Form1.Man.Text = "Pulsar" Then
With Form1.Lev.Items
.Add("Ultra Range")
.Add("IMP Range")
.Add("Twin Range")
End With
End If
End Sub
This fills the combo box lev fine when the Man combo box item "Pulsar" is selected. I then want my users to click a button to generate some labels and stuff. The code is as such:
Button Click Code
Private Sub Generate_Click(sender As Object, e As EventArgs) Handles Generate.Click
If CheckGenerate() = False Then Exit Sub
Dim X = CheckGenerationType(Man.SelectedIndex, Lev.SelectedIndex, Level.Checked, Volume.Checked, ListBox1.SelectedIndex,
Units.SelectedIndex)
Call ParamPage(X)
End Sub
CheckGenerate simply checks that all boxes have been filled in. I pass the informtion from the form to the following function:
Public Function CheckGenerationType(Man As Integer, Lev As Integer, Level As Boolean, Volume As Boolean, TankType As Integer,
MeasurementUnit As Integer) As String
Dim M As Integer
Dim L As Integer
Dim CT As Integer
Dim TT As Integer
Dim Ms As Integer
M = Man
L = Lev
TT = TankType
Ms = MeasurementUnit
If Level = True Then
CT = 0
ElseIf Volume = True Then
CT = 1
End If
CheckGenerationType = CStr(M) + "." + CStr(L) + "." + CStr(CT) + "." + CStr(TT) + "." + CStr(Ms)
End Function
When the lev.selectedindex parameter arrives at this function, it reads -1. Even if the user has selected any of the 3 items. Can anyone explain why this is happening?
I've just tried your code. I get the same result (-1 in lev.SelectedIndex) and this was because jumped using tab through the controls my when i'm hitting the Man or Units Combobox it runs the LevListAdd() and then clears the Lev-ComboBox because of Form1.Lev.Items.Clear().
You should think about your call Man_SelectedIndexChanged_1 or maybe just use something like this:
Public Sub LevListAdd()
If Form1.Man.Text = "Pulsar" Then
Form1.Lev.Items.Clear()
instead of
Public Sub LevListAdd()
Form1.Lev.Items.Clear()
If Form1.Man.Text = "Pulsar" Then
And you should separate the calls from the man and unit ComboBoxes.
Private Sub Unit_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Units.SelectedIndexChanged
' Do something
End Sub
Private Sub Man_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Man.SelectedIndexChanged
Form1.Lev.Items.Clear()
Select Case Form1.Man.Text
Case "Pulsar"
With Form1.Lev.Items
.Add("Ultra Range")
.Add("IMP Range")
.Add("Twin Range")
End With
Case "animals"
With Form1.Lev.Items
.Add("dogs")
.Add("cats")
.Add("birds")
End With
End Select
End Sub

How To Clear CheckedListBox From Previous Selection - VB.NET

Okay so I have a checkedlistbox that when a user selects a item it will print out that item into word. That works perfect. However, I want to give the user the option to not select anything at all, but when the user does not select an item in the checkboxlist, it still prints out the previous selected item into MS word.
Below is my code:
Private Sub ExportContactOkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportContactOkButton.Click
Dim i As Integer
Dim array_Counter_Contacts As Integer
Dim array_size_Contacts As Integer
array_Counter_Contacts = 0
For i = 0 To ExportContactCheckedListBox.Items.Count() - 1
If ExportContactCheckedListBox.GetItemCheckState(i) = CheckState.Checked Then
array_size_Contacts = UBound(SelectedContacts)
ReDim Preserve SelectedContacts(array_size_Contacts + 1)
SelectedContacts(array_Counter_Contacts) = ExportContactCheckedListBox.Items(i)
If Search.debugging = True Then
MsgBox(ExportContactCheckedListBox.Items(i))
End If
array_Counter_Contacts += 1
ExportContactCheckedListBox.Items(i) = ExportContactCheckedListBox.Items(i).ToString.Replace("'", "''")
If array_Counter_Contacts = 1 Then
ContactNames = "" & ExportContactCheckedListBox.Items(i) & ""
Else
ContactNames = String.Concat(ContactNames & "', '" & ExportContactCheckedListBox.Items(i) & "")
End If
End If
Next
If Search.debugging = True Then
MsgBox(ContactNames)
End If
sConnection.Close()
Dispose()
Me.Close()
End Sub
I have tried remove, clear, and I even tried this
Dim i As Integer
For i = 0 To ExportContactCheckedListBox.CheckedIndices.Count - 1
ExportContactCheckedListBox.SetItemChecked(ExportContactCheckedListBox.CheckedIndices(0), False)
Next i
But nothing is working. Can anyone help me? All I want is to be able to have the checkedlistbox forget or clear the checked item after the "OK" button is pressed and the text has already been printed into word.
Use a List(Of String) to store the selection and, of course remember, to reinitialize the list when you hit the ExportContactOkButton
' Declared at the form level....
Dim SelectedContacts as List(Of String)
.....
Private Sub ExportContactOkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportContactOkButton.Click
Dim i As Integer
SelectedContacts = new List(Of String)()
For i = 0 To ExportContactCheckedListBox.Items.Count() - 1
If ExportContactCheckedListBox.GetItemCheckState(i) = CheckState.Checked Then
SelectedContacts.Add(ExportContactCheckedListBox.Items(i))
.....
End If
Next
End Sub
In this way, every time you hit the ExportContactOKButton you reinitialize your list of contacts, loop through the checked items, add the checked one to your list.
A List(Of String) is better because you don't need to know in advance how many items your user selects in the CheckedListBox and continuosly resize the array. You simply add new items to it. And you could always use it like an array
Dim Dim array_Counter_Contacts = SelectedContacts.Count
For i = 0 to array_Counter
Console.WriteLine(SelectedContacts(i))
Next

Bubble sort Array program, Selecting a certain number

I'm trying to find a number out of a random set of X amount of numbers. I don't want you to put it in yourself I would just like suggestions so I can learn.
What my code does it allows me to display any amount of random numbers I would like. I can't search within those numbers and that's where I'm lost.
CODE DISPLAYS NO ERRORS. "Stepping into" is still new to me.
Private Sub GenerateAndSearch(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSort.Click, btnGenerate.Click
Static intDataArray(-1) As Integer
Dim btnButtonClicked As Button = sender
Select Case btnButtonClicked.Tag
Case "Generate Array"
Call GenerateSortedArray(intDataArray)
Me.lstbox1.Items.Clear()
Call DisplayData(intDataArray, Me.lstbox1, "Sorted array:")
Case "Search Array"
Dim intNumToFind As Integer = Val(Me.txtNumElements.Text)
Dim intNumFoundIndex As Integer
intNumFoundIndex = BinarySearch(intDataArray, intNumToFind)
If intNumFoundIndex = -1 Then
Me.Label1.Text = "Number not found."
Else
Me.Label1.Text = "Number found at index" & intNumFoundIndex
End If
End Select
End Sub