Dim Cans(7) As String
Dim money As Decimal
Public Sub Main()
Cans(0) = "Pepsi"
Cans(1) = "Pepsi MAX"
Cans(2) = "Sprite"
Cans(3) = "Mountain Dew"
Cans(4) = "Fanta"
Cans(5) = "Coca Cola"
Cans(6) = "Coke Diet"
Cans(7) = "Coke Vanilla"
End Sub
Private Sub ButtonPepsi_Click(sender As System.Object, e As System.EventArgs) Handles ButtonPepsi.Click
If money >= 0.8 Then
money = money - 0.8
TextBoxItem.TextAlign = HorizontalAlignment.Center
TextBoxItem.Text = "You brought a " & Cans(0)
TextboxCredit.Text = "£" & money
End If
End Sub
Every time I click the button to buy a pepsi, it just says in the textbox "You bought a " and it should say "Pepsi" but it does not work. Anybody got any ideas?
VB.NET has many methods of starting your application. Which one is used can be set in the project properties. The most common ones are:
Sub Main: Here, a sub Main in a module is called. Then, it's the sub's responsibility to start forms that should be shown.
Start Form: This is probably the option you are using. A specific form is opened and shown to the user. No Sub Main is executed.
How do you solve your problem? If you want to initialize the array when the window is opened, just use the Form.Load event for that:
Public Sub Form_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Cans(0) = "Pepsi"
Cans(1) = "Pepsi MAX"
...
End Sub
Main is never called, that's why your array elements are all empty string. I think you are mixing console and windows applications. You can place a call to Main in Sub New, after InitializeComponent. Or better, move all that code after InitializeComponent, to avoid confusion.
Or just declare your Cans array like this:
Dim Cans() As String = {"Pepsi", ..., "Coke Vanilla"}
Then you don't need Main at all.
Try this,
Private Sub ButtonPepsi_Click(sender As System.Object, e As System.EventArgs) Handles ButtonPepsi.Click
Main()
If money >= 0.8 Then
money = money - 0.8
TextBoxItem.TextAlign = HorizontalAlignment.Center
TextBoxItem.Text = "You brought a " & Cans(0)
TextboxCredit.Text = "£" & money
End If
End Sub
Related
I am very new to coding so please forgive me.
I have saved some example strings in an array:
Dim intArray(0 To 2) As String
intArray(0) = "I will be on time for class"
intArray(1) = "I will be prepared for class"
intArray(2) = "I will listen to the teacher and follow instructions"
lblTestSWPB.Text = intArray(0)
I know that it works when I click the button to generate for (0) - obviously.Is there a way to add something to make the label display a string at random from the array?
You may use something like: Random class
Dim rnd As New Random 'Make sure that you declare it as New,
'otherwise, it thorws an Exception(NullReferenceException)
Dim intArray(0 To 2) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
intArray(0) = "I will be on time for class"
intArray(1) = "I will be prepared for class"
intArray(2) = "I will listen to the teacher and follow instructions"
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
lblTestSWPB.Text = intArray(rnd.Next(0, 3))
End Sub
Note that rnd.Next is a Function that returns a random Integer from the minimum is the inclusive lower bound and the maximum is the exclusive upper bound.(Thanks to #Enigmativity for the correction.) Click this link if this answer is still unclear for you
I have a VB.Net program that loops through array's to try to figure out where bottles are on a "conveyor". The point of this program is to visually show staff, how the conveyor works using VB.net and Labels. It's extremely difficult to explain, so I’ll do my best.
Bottle_Number(10) Bottle_Position(128)
There are 10 bottles that I want to track at all 128 stops on the conveyor.
We have a conveyor that can only fit 10 bottles. I need to track the position of each of the 10 bottles. Once bottle 11 comes on - That means bottle 1 is completed and off the conveyor. So, bottle 11 becomes bottle 1, so I need to reset the position of bottle1 to 0, and continue tracking bottles 2-9 while also tracking bottle 11(Not bottle 1). Once bottle 12 comes on it becomes bottle 2, and I need to reset the position of bottle 2 to '0' and continue tracking all bottles.
Any help would be appreciated.
Here is my code:
Public Class frmMain
Dim Product_Position(10) As Integer
Dim Inches_Per_Pulse As Integer
Dim PulseNumber As Integer
Dim Product_Counter As Integer
Dim Product_Location(10) As Integer
Dim Function1 As Integer
Dim Function2 As Integer
Dim Function3 As Integer
Dim Function4 As Integer
Dim Function5 As Integer
Dim Function6 As Integer
Dim Function7 As Integer
Dim Function8 As Integer
Dim Function9 As Integer
Dim Function10 As Integer
Dim Product_in_Tunel As Integer
Dim test As Integer
Dim Roll_OVer As Boolean
Dim Product_Counter_Test As Integer
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
lblStatus.BackColor = Color.Green
lblStatus.Text = "Conveyor Status: Running"
End Sub
Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
lblStatus.BackColor = Color.Red
lblStatus.Text = "Conveyor Status: Off"
End Sub
Private replace_next As Integer
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If Product_Counter = 10 Then
replace_next += 1
If replace_next > 10 Then
replace_next = 1 ' replace them in turn 1..10, then loop back to 1
Product_Position(replace_next) = 0 ' put initial position here
End If
End If
Product_Counter = Product_Counter + 1
If Product_Counter > 10 Then
Product_Counter = 1
Roll_over = True
End If
'MsgBox(Product_Counter)
'MsgBox(replace_next)
End Sub
Private Sub btnPulse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPulse.Click
Get_Location()
End Sub
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
PulseNumber = "0"
Inches_Per_Pulse = "1"
Roll_OVer = False
'MsgBox("Test")
End Sub
Public Sub Get_Location()
'MsgBox(Product_Counter)
If Roll_OVer = True Then
Product_Counter_Test = 10
'MsgBox("i'm stuck here")
End If
If Roll_OVer = False Then
Product_Counter_Test = Product_Counter
End If
'MsgBox(Product_Counter_Test)
'MsgBox("am I here - Yes")
For test = 1 To Product_Counter_Test
'MsgBox("This works")
Product_Position(test) = Product_Position(test) + Inches_Per_Pulse
Next
PulseNumber = PulseNumber + 1
ClearLabels()
lblProduct1Position.Text = Product_Position(1)
lblProduct2Position.Text = Product_Position(2)
lblProduct3Position.Text = Product_Position(3)
lblProduct4Position.Text = Product_Position(4)
lblProduct5Position.Text = Product_Position(5)
lblProduct6Position.Text = Product_Position(6)
lblProduct7Position.Text = Product_Position(7)
lblProduct8Position.Text = Product_Position(8)
lblProduct9Position.Text = Product_Position(9)
lblProduct10Position.Text = Product_Position(10)
End Sub
Public Sub ClearLabels()
lblProduct1Position.Text = ""
lblProduct2Position.Text = ""
lblProduct3Position.Text = ""
lblProduct4Position.Text = ""
lblProduct5Position.Text = ""
lblProduct6Position.Text = ""
lblProduct7Position.Text = ""
lblProduct8Position.Text = ""
lblProduct9Position.Text = ""
lblProduct10Position.Text = ""
End Sub
The Pulse button is what is actually driving the conveyor, each pulse (click of the button) means the conveyor is moving forward.
Right now once the program gets to bottle 11, it resets and only moves forward the "new" bottle (bottle1). It should continue incrementing the remaining bottles until they reach the end and do the same for them - Reset the position to 0 and begin counting again.
As far as I understand it, once you have 11 bottles, you don't want to reset to only one bottle, but instead still have 10 bottles, and replace one of them. You'll need a second variable to keep track of which is to be replaced.
So instead of :
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Product_Counter = Product_Counter + 1
If Product_Counter > 10 Then Product_Counter = 1
End Sub
It would be something like:
Private Replace_Next as Integer = 0
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If Product_Counter = 10 Then
Replace_Next += 1
If Replace_Next > 10 Then Replace_Next = 1 ' replace them in turn 1..10, then loop back to 1
Product_Position(Replace_Next) = .... ' put initial position here
Else
Product_Counter = Product_Counter + 1
End If
End Sub
Your conveyor is FIFO (first-in, first-out), so rather than constantly shifting, reindexing and/or rebuilding (=reset?) an array to make it seem like it is FIFO, Net includes the Queue(Of T) collection which is FIFO.
A LinkedList(Of T) could also be used. A plain List(Of T) would also work, but if the add/remove frequency is high, that will result in the same inefficient shifting taking place under the hood that you have with an array.
The only issue is enforcement of the size limit, which is easily handled with a small class wrapper. I assume there is something interesting or identifiable about the bottles other than their position. The test code uses a sequence ID and the contents.
Friend Class Bottle
Public Property Contents As String
Public Property SequenceID As Int32
' etc
Public Overrides Function ToString() As String
Return String.Format("{0}: ({1})", SequenceID.ToString("00"), Contents)
End Function
End Class
You likely have more relevant information to show. The, the collection class:
Friend Class BottleQueue
Private mcol As Queue(Of Bottle)
Private lbls As Label()
Private MaxSize As Int32 = 10 ' default
Public Sub New(size As Int32)
MaxSize = size
mcol = New Queue(Of Bottle)
End Sub
Public Sub New(size As Int32, l As Label())
Me.New(size)
lbls = l
End Sub
Public Sub Add(b As Bottle)
mcol.Enqueue(b)
Do Until mcol.Count <= MaxSize
mcol.Dequeue()
Loop
UpdateDisplay()
End Sub
Public Function Peek() As Bottle
Return mcol.ElementAtOrDefault(0)
End Function
Public ReadOnly Property Count() As Int32
Get
Return mcol.Count
End Get
End Property
Public Function Remove() As Bottle
Dim b As Bottle = Nothing
If mcol.Count > 0 Then
b = mcol.Dequeue
UpdateDisplay()
End If
Return b
End Function
Private Sub UpdateDisplay()
Dim n As Int32
If lbls Is Nothing OrElse lbls.Count = 0 Then
Return
End If
For n = 0 To mcol.Count - 1
lbls(n).Text = mcol.ElementAtOrDefault(n).ToString
Next
For n = n To lbls.Count - 1
lbls(n).Text = "(empty)"
Next
End Sub
Public ReadOnly Property GetQueue As Bottle()
Get
Return mcol.ToArray()
End Get
End Property
End Class
The class has 2 display means built in. One updates a set of labels. Since it is a collection, it also provides a way to get the current collection in order for a collection type control such as a Listbox. An even better way would be if the collection itself was "observable", so it could be used as a datasource.
It also provides a way to Removethe next bottle manually. Removing from a specific index (e.g. Remove(3)) is antithetical to a Queue, so it isnt implemented.
test code:
' form level vars:
Private BottleQ As BottleQueue
Private BottleID As Int32 = 7
' form load, passing the labels to use
' using a queue size of FIVE for test
BottleQ = New BottleQueue(5, New Label() {Label1, Label2, Label3, Label4, Label5})
Adding an item:
Dim material = {"Napalm", "Beer", "Perfume", "Pepsi", "Cyanide", "Wine"}
' add new bottle with something in it
BottleQ.Add(New Bottle With {.Contents = material(RNG.Next(0, material.Count)),
.SequenceID = BottleID})
BottleID += 1
' clear and show the contents in a listbox:
lbQueView.Items.Clear()
lbQueView.Items.AddRange(BottleQ.GetQueue)
The BottleId arbitrarily starts at 7, the contents are random. BTW, material shows just about the only way I ever use an array: when the contents are fixed and known ahead of time. In almost all other cases, a NET collection of one sort or another, is probably a better choice.
Because it is not an observable collection (and that is a little at odds with the FIFO nature), the listbox needs to be cleared each time. That could be internal to the class like the label display is. Results:
On the right, the first 5 are shown in order; 3 clicks later, the result is on the left: everything moved up 3 and 3 new items have been added.
Note: If the code using this needs to know when/which Bottle is removed from the conveyor, the class could include a ItemRemoved event which provides the item/Bottle just removed when adding forces one out. That is probably the case, but the question doesnt mention it.
Trying to knock out a project that's hanging my code without re-writing the entire thing. In it, I just need to populate an array with the information already in the Names combobox in order to proceed. As I'm not using .NET, my options are limited.
(The end result)*Add a button named “btnShowBalance” displaying the text “ShowBalance.” Write code in its event handler asking the user to enter a client’s name (InputBox). Search the names array for the name entered. If the name is found, use its location to retrieve the matching balance from the balances array. Display the client’s name and balance if the client exists; otherwise, display a not-found message. ****
Public Class Form1
Dim Balances(7) As Decimal
Dim Names(7) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cboNames.Items.Add("John One")
cboNames.Items.Add("Jack Two")
cboNames.Items.Add("John Three")
cboNames.Items.Add("Jack Four")
cboNames.Items.Add("John Five")
cboNames.Items.Add("Jack Six")
cboNames.Items.Add("John Seven")
cboNames.Items.Add("Jack Eight")
cboBalances.Items.Add("235.50")
cboBalances.Items.Add("78943.98")
cboBalances.Items.Add("230781.10")
cboBalances.Items.Add("78362.00")
cboBalances.Items.Add("12097.20")
cboBalances.Items.Add("89267.34")
cboBalances.Items.Add("34959.06")
cboBalances.Items.Add("559284.50")
For i = 0 To cboNames.Items.Count - 1
Names(i) = cboNames.Text
Next
For i = 0 To cboBalances.Items.Count - 1
Names(i) = cboBalances.SelectedItem
Next
End Sub
Private Sub btnShowBalance_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowBalance.Click
Dim strResult As String
strResult = InputBox("Enter the name of the customer", "Balance Finder")
For i = 0 To Names.Length - 1
If strResult = Names(i) Then
MessageBox.Show(Names(i).ToString & " " & Balances(i).ToString)
End If
Next
End Sub
End Class
I have create multiple choice system where the user need to choose answer from 4 radiobutton before navigate to next question by clicking next button.
So, the I have problem in storing the selected radiobutton into database. At first I create a table where I create columns to store each answer but it failed. Now, I'm stuck. Please give any suggestion where i can store the answer.
Here I provide the code to load the question
p/s: I know i should ask this on different thread but I also stuck on how to randomize the radiobutton.
Public Property Counter() As Integer
Get
Return IIf(ViewState("counter") Is Nothing, 1, CInt(ViewState("counter")))
End Get
Set(ByVal value As Integer
ViewState("counter") = value
End Set
End Property
Protected Sub Next_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Counter += 1
question()
clean()
End Sub
Sub question()
conn.Open()
Dim cmd As New SqlCommand("Select * From ques Where Id=#Id", conn)
cmd.Parameters.AddWithValue("#Id", Counter)
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
If dr1.Read() Then
Me.lblquestion.Text = dr1("question")
Me.RadioButton1.Text = dr1("right")
Me.RadioButton2.Text = dr1("wrong")
Me.RadioButton3.Text = dr1("wrong2")
Me.RadioButton4.Text = dr1("wrong3")
Else
conn.Close()
Counter += 1
question()
End If
conn.Close()
End Sub
Sub clean()
RadioButton1.Checked = False
RadioButton2.Checked = False
RadioButton3.Checked = False
RadioButton4.Checked = False
Next.Enabled = False
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
question()
End Sub
Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
Next.Enabled = True
End Sub
Protected Sub RadioButton2_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged
Next.Enabled = True
End Sub
Protected Sub RadioButton3_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton3.CheckedChanged
Next.Enabled = True
End Sub
Protected Sub RadioButton4_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton4.CheckedChanged
Next.Enabled = True
End Sub
End Class
I would have a database structure like this:
TblQuizes
Quiz_Id int
Quiz_Name nvarchar(200) -- or any other number that meets your demands
TblQuestions
Question_Id int
Question_Quiz_Id int --(FK To TblQuizes)
Question_Text nvarchar(200) -- or any other number that meets your demands
TblAnswers
Answer_Id int
Answer_Question_Id int --(FK To TblQuestions)
Answer_Text nvarchar(200) -- or any other number that meets your demands
Answer_IsCorrect bit
TblResults
Result_Id int
Result_Quiz_Id int -- (FK to TblQuizes) (not even needed, just to convenience)
-- Add user data in this table if you need it
TblResultDetails
ResultDetails_Id int
ResultDetails_Result_Id int --(FK to TblResults)
ResultDetails_Answer_Id int (FK to TblAnswers)
Now what I would do is create a new record in TblResults for every user that answers the quiz, and store the users answers in TblResultDetails.
On this basic structure you can create views to give you the entire data you need to show the quiz to the user, or to show him how well he answered your questions, and so on. you can also see very easily if a user did not complete the quiz, just by comparing the number of records in TblQuetions and TblResultDetails for a specific quiz id.
Also, if you ever want to have questions with only 2 answer, or 6 answers, you don't have to change anything in the database structure or in your code to have that.
Got a small problem. I don't know how to search one array so I can pull that same array number from the other 2 arrays. I know how to test for a lot of stuff so that won't be a problem.
The end result on this project is the user will place the amount they are willing to pay for a make of the car and the page will display the data. HOWEVER I don't know how to search the carArray() to find the index number and use that index number to find the other stuff. I did find something that did this (somewhat) earlier but I don't know how to modify it for me to keep that index number as a int and use it to search and display the other arrays.
I will need this in future projects later.
Public Class paymentPage
Private Sub car_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles car.TextChanged
End Sub
Private Sub price_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles price.TextChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim carArray() As String = {"Ford", "Chevy", "Mazda"}
Dim sellAmount() As Decimal = {32700, 35625, 24780}
Dim leaseAmount() As Decimal = {425, 505, 385}
End Sub
End Class
Why not make this a class object? Easier to reuse later.
Public Class Car
Public Property Make As String
Public Property Value As Double
Public Property Lease As Double
End Class
Then make a collection of them:
Private cars As New List(Of Car)
cars.Add(New Car With {.Make = "Ford", .Value = 32700, .Lease = 425})
cars.Add(New Car With {.Make = "Chevy", .Value = 35625, .Lease = 505})
cars.Add(New Car With {.Make = "Mazda", .Value = 24780, .Lease = 385})
For your requirements:
Private Function getIndexByName(make As string) As Integer
Dim result As Integer = -1
For i As Integer = 0 To carArray.Length -1
If carArray(i) = make Then
result = i
Exit for
End If
Next
Return Result
End Function
Usage:
Dim mazdalease = leaseAmt(getIndexByName("Mazda"))
Dim cars as new List(Of Car)({car1,car2,car3})
Dim indexOfCar2 = Array.IndexOf(cars.ToArray(),car2)
Since its dirt simple to convert to an array then you can use the built in function. Keep in mind that you need to override GetHash and Equals to get this to work properly.