Textbox and Class - vb.net

Have trouble connecting exception to textbox input - Program should only accept "IL", "MO" or "WI" - But it's accepting every input. Everything I tried I'm hitting a brick wall - I know the solution is there, I just need some help. Thanks
Form Codes
Public Class Form1
Dim packages(4) As Packages
Dim pkg As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
packages(0) = New Packages("Z111", "Eau Claire", "WI")
packages(1) = New Packages("Z121", "Vicki Vale", "IL")
packages(2) = New Packages("Z131", "Sammy Davis", "MO")
packages(3) = New Packages("Z141", "Jon Smith", "IL")
packages(4) = New Packages("Z151", "Suzie Cassidy", "WI")
DisplayInfo()
End Sub
Sub DisplayInfo()
txtID.Text = packages(pkg).PackageID
txtCity.Text = packages(pkg).DestinationCity
txtState.Text = packages(pkg).DestinationState
lblPackageCount.Text = "Package # " & pkg + 1
End Sub
Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
pkg = 0
DisplayInfo()
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If pkg > 0 Then
pkg -= 1
DisplayInfo()
End If
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If pkg < packages.Length - 1 Then
pkg += 1
DisplayInfo()
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
pkg = packages.Length - 1
DisplayInfo()
End Sub
Private Sub btnSaveChanges_Click(sender As Object, e As EventArgs) Handles btnSaveChanges.Click
Try
packages(pkg).PackageID = txtID.Text
packages(pkg).DestinationCity = txtCity.Text
packages(pkg).DestinationState = txtState.Text
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
Class Codes
Public Class Packages
Private packID As String
Private desCity As String
Private desState As String
Sub New(id As String, city As String, state As String)
packID = id
desCity = city
desState = state
End Sub
Public Property PackageID As String
Get
Return packID
End Get
Set(value As String)
packID = value
End Set
End Property
Public Property DestinationCity As String
Get
Return desCity
End Get
Set(value As String)
desCity = value
End Set
End Property
Public Property DestinationState As String
Get
Return desState
End Get
Set(value As String)
If desState = "IL" Then
desState = value
ElseIf desState = "WI" Then
desState = value
ElseIf desState = "MO" Then
desState = value
Else
Throw New Exception("Can not deliver to this state")
End If
End Set
End Property
End Class

Your immediate problem is you're checking the property value instead of the passed value. Something like this should work:
Set(value As String)
'This creates a temporary string array of available states and checks if _
the value passed is contained in the array
If {"IL","WI", "MO"}.Contains(value)Then
desState = value
Else
Throw New Exception("Can not deliver to this state")
End If
End Set
If this is something you may need to change you could make the array a property.

Related

Looping through Playlist

I am having trouble looping through my playlist of mp3 tracks.
Can anybody shed some light on where I am going wrong. This is the code. It play the first track, but then stops.
Code has been edited 011020
' The following Menu Item plays the full list of mp3s in the list box
Private Sub PlayListToolStripMenuItem_Click(sender As Object, e As EventArgs)
Handles PlayListToolStripMenuItem.Click
FromDictionary = False
PlaySongsFromListBox()
End Sub
Private Sub PlaySongsFromListBox()
'MsgBox("Index Counter = " & NextIndex)
'MsgBox("Total No of Tracks = " & ListBox1.Items.Count)
If NextIndex = ListBox1.Items.Count Then
NextIndex = 0
MessageBox.Show("All music has been played")
Exit Sub
End If
Dim item As KeyValuePair(Of String, String) =
DirectCast(ListBox1.Items(NextIndex), KeyValuePair(Of String, String))
Dim SongPath = Path.Combine(item.Value, item.Key)
PlayASong(SongPath)
End Sub
Private Sub PlayASong(SongPath As String)
MsgBox("Playing Track: " & SongPath)
CurrentMediaStreamName = SongPath
MediaPlayer1.URL = SongPath
MediaPlayer1.Ctlcontrols.play()
MsgBox("Playing Track: " & SongPath)
End Sub
Private Sub MediaPlayer1_PlayStateChange(sender As Object, e As
AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles
MediaPlayer1.PlayStateChange
If MediaPlayer1.playState = WMPLib.WMPPlayState.wmppsMediaEnded Then
NextIndex += 1
PlaySongsFromListBox()
End If
End Sub
At the class level (Form1) I declared 4 variables that are used in more than one method.
In the Form.Load I filled the MusicDictionary. You may be filling this from a database or text file. I also bound the ListBox to the dictionary. The ListBox.DataSource cannot take a Dictionary directly but a BindingSource can handle it.
PlayASong simply does what it says.
PlaySongsFromDictionary first checks if we have come to the end of the Dictionary. Note that I reset NextIndex back to 0. I used Path.Combine to get the path for the song. Notice that in one dictionary entry, I left out a back slash at the end of the directories and in the other entry I included the backslash. Path.Combine accepted both and added a back slash where necessary. Also notice that the index is applied to the Keys collection and the Values collection of the Dictionary not the Dictionary itself. If we tried to apply the index to the dictionary it would be trying to look for the Key inside the brackets. Default Public Property Item(key As TKey) As TValue
PlaySongsFromListBox casts the list box item (which is an object) back to its underlying type, KeyValuePair.
Finally, the important part! I used the MediaEnded event of the MediaPlayer1 to determine when to play the next song. Here I incremented the index and called the one of the PlaySongs... methods.
Private NextIndex As Integer
Private WithEvents MediaPlayer1 As New MediaPlayer
Private MusicDictionary As New Dictionary(Of String, String)
Private FromDictionary As Boolean
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MusicDictionary.Add("2018-11-27_-_Track_A_-_FesliyanStudios.com_By_Stephen_Bennett.mp3", "C:\Users\maryo\Documents\Marys Music")
MusicDictionary.Add("file_example_MP3_700KB.mp3", "C:\Users\maryo\Documents\Marys Music\")
ListBox1.DataSource = New BindingSource(MusicDictionary, Nothing)
ListBox1.DisplayMember = "Key"
ListBox1.ValueMember = "Value"
End Sub
Private Sub PlayASong(SongPath As String)
MediaPlayer1.Open(New Uri(SongPath))
MediaPlayer1.Play()
End Sub
Private Sub PlaySongsFromDictionary()
If NextIndex = MusicDictionary.Count Then
NextIndex = 0
MessageBox.Show("All music has been played")
Exit Sub
End If
Dim SongPath = Path.Combine(MusicDictionary.Values(NextIndex), MusicDictionary.Keys(NextIndex))
PlayASong(SongPath)
End Sub
Private Sub PlaySongsFromListBox()
If NextIndex = ListBox1.SelectedItems.Count Then
NextIndex = 0
MessageBox.Show("All music has been played")
Exit Sub
End If
Dim item As KeyValuePair(Of String, String) = DirectCast(ListBox1.SelectedItems(NextIndex), KeyValuePair(Of String, String))
Dim SongPath = Path.Combine(item.Value, item.Key)
PlayASong(SongPath)
End Sub
Public Sub MediaPlayers1_MediaEnded() Handles MediaPlayer1.MediaEnded
NextIndex += 1
If FromDictionary Then
PlaySongsFromDictionary()
Else
PlaySongsFromListBox()
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FromDictionary = False
PlaySongsFromListBox()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
FromDictionary = True
PlaySongsFromDictionary()
End Sub
The problem with the MP3's not looping was solved using the following invoke method
If e.newState = WMPLib.WMPPlayState.wmppsStopped Then
Me.BeginInvoke(New Action(AddressOf NextSong))
End If
Found at the following location Function call only works when MessageBox.Show() is included?

SSL/TLS connection not working in webclient after being in background

So if I use my program normally no error occurs. But if it is in background for longer time and I use the webclient to visit a web address it immidiately throws could not create a SSL/TLS secure channel error but if I try again the error dissapears. I already set the TLS to 1.2 and expect100continue to false.
Imports System.Net
Imports System.Text.RegularExpressions
Public Class CinemaLinker
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MaximizeBox = False
If Not HaveInternetConnection() Then
MessageBox.Show("Warning: no internet connection!")
End If
ServicePointManager.Expect100Continue = False
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
End Sub
Public Property TextFromBox As String
Public Property StatusLink As String
Private Client As New WebClient
Private GoogleSearch = "****"
Private BingSearch = "*****"
Private AskSearch = "*****"
Private Sub Search() Handles Button1.Click
Cursor.Current = Cursors.WaitCursor
TextFromBox = RichTextBox1.Text
If Button3.Enabled And Button4.Enabled Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please choose a category!")
Exit Sub
End If
If TextFromBox.Contains("Type movie or tv series name here") Or String.IsNullOrEmpty(TextFromBox) Or String.IsNullOrWhiteSpace(TextFromBox) Then
Cursor.Current = Cursors.[Default]
If Not Button3.Enabled Then
MessageBox.Show("Please type the name of the movie!")
Exit Sub
End If
If Not Button4.Enabled Then
If Not (String.IsNullOrEmpty(RichTextBox3.Text) Or String.IsNullOrWhiteSpace(RichTextBox3.Text) Or RichTextBox3.Text.Contains("E")) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please type the name of the tv series! Episode number missing!")
Exit Sub
End If
If String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Or RichTextBox2.Text.Contains("S") Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please type the name of the tv series! Season and episode numbers missing!")
Exit Sub
End If
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please type the name of the tv series!")
Exit Sub
End If
End If
If Not Button4.Enabled Then
If String.IsNullOrEmpty(RichTextBox3.Text) Or String.IsNullOrWhiteSpace(RichTextBox3.Text) Or RichTextBox3.Text.Contains("E") Then
If String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Or RichTextBox2.Text.Contains("S") Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Season and episode numbers missing!")
Exit Sub
End If
Cursor.Current = Cursors.[Default]
MessageBox.Show("Episode number missing!")
Exit Sub
ElseIf String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Or RichTextBox2.Text.Contains("S") Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Season number missing!")
Exit Sub
End If
End If
If Not HaveInternetConnection() Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("No internet connection!")
Exit Sub
End If
Dim ImdbURL As String = getIMDbUrl(TextFromBox)
If Not ImdbURL.Contains("******") And Not Button3.Enabled Then
ImdbURL = getIMDbUrl(TextFromBox) + " movie"
If Not ImdbURL.Contains("***") And Not Button3.Enabled Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Movie not found! Please add the year in the name!")
Exit Sub
End If
End If
If Not ImdbURL.Contains("***") And Not Button4.Enabled Then
ImdbURL = getIMDbUrl(TextFromBox) + " TV series"
If Not ImdbURL.Contains("****") And Not Button4.Enabled Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("TV series not found! Please add the year in the name!")
Exit Sub
End If
End If
Dim LinkFinal As String = (GetLink(ImdbURL))
If String.IsNullOrEmpty(LinkFinal) Or String.IsNullOrWhiteSpace(LinkFinal) Then
Cursor.Current = Cursors.[Default]
Exit Sub
End If
Clipboard.SetText(LinkFinal)
MessageBox.Show("Link in clipboard. Paste it into desired browser!")
TextFromBox = String.Empty
StatusLink = "0"
Cursor.Current = Cursors.[Default]
End Sub
Public Function HaveInternetConnection() As Boolean
Dim result As Boolean
Try
result = My.Computer.Network.Ping("www.google.com")
Catch ex As Exception
result = False
End Try
Return result
End Function
Private Function GetIP() As String
Return Client.DownloadString("https://api.ipify.org").ToString()
End Function
Private Function matchAll(ByVal regex As String, ByVal html As String, ByVal Optional i As Integer = 1) As ArrayList
Dim list As ArrayList = New ArrayList()
For Each m As Match In New Regex(regex, RegexOptions.Multiline).Matches(html)
list.Add(m.Groups(i).Value.Trim())
Next
Return list
End Function
Private Function getIMDbUrl(MovieName As String, Optional searchEngine As String = "google") As String
Dim address As String = GoogleSearch + MovieName
If searchEngine.ToLower().Equals("bing") Then
address = BingSearch + MovieName
End If
If searchEngine.ToLower().Equals("ask") Then
address = AskSearch + MovieName
End If
Dim html As String = Client.DownloadString(address)
Dim arrayList As ArrayList = matchAll("<a href=""(*****\d{7}/)"".*?>.*?</a>", html, 1)
If arrayList.Count > 0 Then
Return CStr(arrayList(0))
ElseIf searchEngine.ToLower().Equals("google") Then
Return getIMDbUrl(MovieName, "bing")
ElseIf searchEngine.ToLower().Equals("bing") Then
Return getIMDbUrl(MovieName, "ask")
Else
Return String.Empty
End If
End Function
Private Function GetLink(ImdbURL As String) As Object
Dim ID = ImdbURL.Replace("*****/", "")
ID = ID.Replace("/", "")
Dim result As Object
If StatusLink = "1" Then
Cursor.Current = Cursors.[Default]
Exit Function
ElseIf Not Button4.Enabled Then
Dim SeasonNumber As String = "&s=" + RichTextBox2.Text
Dim EpisodeNumber As String = "&e=" + RichTextBox3.Text
Dim TVSeasonNumber As String = "&tv=1" + SeasonNumber
If Not Client.DownloadString("*****/" & ID).Contains(">Episode Guide<") Then
ImdbURL = getIMDbUrl(TextFromBox + " TV series")
StatusLink = "1"
If String.IsNullOrEmpty(ImdbURL) Or String.IsNullOrWhiteSpace(ImdbURL) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("TV series not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
ID = ImdbURL.Replace("*****", "")
ID = ID.Replace("/", "")
result = (GetLink(ImdbURL))
If String.IsNullOrEmpty(result) Or String.IsNullOrWhiteSpace(result) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("TV series not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
Return result.ToString()
result = String.Empty
Exit Function
End If
End If
Else
Dim address As String = "******" & ID & TVSeasonNumber & "&ip=" & GetIP()
Dim token As String = Client.DownloadString(address)
result = "*****" & ID & TVSeasonNumber & EpisodeNumber & "&ticket=" & token
Return result.ToString
Exit Function
End If
ElseIf Not Button3.Enabled Then
If Client.DownloadString("****" & ID).Contains(">Episode Guide<") Then
ImdbURL = getIMDbUrl(TextFromBox + " movie",)
StatusLink = "1"
If String.IsNullOrEmpty(ImdbURL) Or String.IsNullOrWhiteSpace(ImdbURL) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Movie not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
ID = ImdbURL.Replace("****", "")
ID = ID.Replace("/", "")
result = (GetLink(ImdbURL))
If String.IsNullOrEmpty(result) Or String.IsNullOrWhiteSpace(result) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Movie not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
Return result.ToString()
result = String.Empty
Exit Function
End If
End If
Else
Dim address2 As String = "****" & ID & "&ip=" & GetIP()
Dim token2 As String = Client.DownloadString(address2)
result = "****" & ID & "&ticket=" & token2
Return result.ToString
result = String.Empty
Exit Function
End If
End If
#Disable Warning BC42105 ' Function doesn't return a value on all code paths
End Function
Private Sub RichTextBox1_MouseClick(sender As Object, e As EventArgs) Handles RichTextBox1.GotFocus
If RichTextBox1.Text.Contains("Type movie or tv series name here") Then RichTextBox1.Text = String.Empty
End Sub
Private Sub RichTextBox2_MouseClick(sender As Object, e As EventArgs) Handles RichTextBox2.GotFocus
If RichTextBox2.Text.Contains("S") Then RichTextBox2.Text = String.Empty
End Sub
Private Sub RichTextBox3_MouseClick(sender As Object, e As EventArgs) Handles RichTextBox3.GotFocus
If RichTextBox3.Text.Contains("E") Then RichTextBox3.Text = String.Empty
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Button3.Enabled = False
Button4.Enabled = True
RichTextBox1.Enabled = True
RichTextBox2.Enabled = False
RichTextBox3.Enabled = False
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Button4.Enabled = False
Button3.Enabled = True
RichTextBox1.Enabled = True
RichTextBox2.Enabled = True
RichTextBox3.Enabled = True
End Sub
Private Sub RichTextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox2.KeyPress
If Char.IsLetter(e.KeyChar) Then
e.Handled = True
End If
If CType(e, KeyPressEventArgs).KeyChar = vbCr Then
Search()
End If
End Sub
Private Sub RichTextBox3_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox3.KeyPress
If Char.IsLetter(e.KeyChar) Then
e.Handled = True
End If
If CType(e, KeyPressEventArgs).KeyChar = vbCr Then
Search()
End If
End Sub
Private Sub RichTextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
If CType(e, KeyPressEventArgs).KeyChar = vbCr Then
Search()
End If
If Char.IsUpper(e.KeyChar) Then e.KeyChar = Char.ToLower(e.KeyChar)
End Sub
Private Sub RichTextBox1_Lostfocus(sender As Object, e As EventArgs) Handles RichTextBox1.LostFocus
If String.IsNullOrEmpty(RichTextBox1.Text) Or String.IsNullOrWhiteSpace(RichTextBox1.Text) Then
RichTextBox1.Text = "Type movie or tv series name here..."
End If
End Sub
Private Sub RichTextBox2_Lostfocus(sender As Object, e As EventArgs) Handles RichTextBox2.LostFocus
If String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Then
RichTextBox2.Text = "S:"
End If
End Sub
Private Sub RichTextBox3_Lostfocus(sender As Object, e As EventArgs) Handles RichTextBox3.LostFocus
If String.IsNullOrEmpty(RichTextBox3.Text) Or String.IsNullOrWhiteSpace(RichTextBox3.Text) Then
RichTextBox3.Text = "E:"
End If
End Sub
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
StatusLink = "0"
End Sub
Private Sub RichTextBox2_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox2.TextChanged
StatusLink = "0"
End Sub
Private Sub RichTextBox3_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox3.TextChanged
StatusLink = "0"
End Sub
End Class
all of the ***** are https website addresses.
Tried switching the Net version to 4.7. Did not help. It is also legal in my country to stream (interior minister dropped a bomb on the DMCA here lol) and this is streaming only. The code is not operational so i had not given you anything dangerous if it is illegal in yours.

Add array values from textboxes and display in a label

enter image description here <<< my interface
I am working on something for my exam next week.
I must use Visual Basic. I am supposed to create an array with an integer and string. Integer = distance String = name. there will be 2 textboxes, 2 labels and 2 buttons.
txtname.text, txtdistance.text, lblname, lbldistance, btninputdata and btnshowcontent
btninputdata should be disabled after filling the 30 arrays and making btnshowcontent to be visible and show all the 30 values (inserted values via textboxes) in lblname and lbldistance.
Whereas they both need to be inserted via a textbox store into the array and then using a btnshowcontent the stored array should be displayed on separate labels of name and distance.
My codes:
Public Class Form1
Dim ara(29) As String
Private Sub Form1_Load(sender As Object, e As EventArgs)
End Sub
Private Sub btninputdata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btninputdata.Click
If txtname.Text <> "" Then
For h As Integer = 0 To 29
If ara(h) = "" Then
ara(h) = txtname.Text
txtname.Clear()
Exit Sub
End If
Label1.Text = ara.ToString()
Next
MsgBox("arry full")
btninputdata.Visible = False
btnshowcontent.Visible = True
End If
End Sub
Private Sub btnshowcontent_Click(sender As Object, e As EventArgs) Handles btnshowcontent.Click
'ListBox1.Items.Clear()
'ListBox1.Items.AddRange(ara)
''Label1.Text &= ara(I) & ""
End Sub
Private Sub Form1_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
You'll want to start with something like this. Not sure how you're really trying to display everything, though. You'd probably want to do validation on the distance field also.
Public Class Form1
Dim Ara As New List(Of MyGroup)
Private Sub btninputdata_Click(sender As Object, e As EventArgs) Handles btninputdata.Click
If txtName.Text.Trim() <> String.Empty Then
Ara.Add(New MyGroup With {.Name = txtName.Text, .Distance = txtDistance.Text})
If Ara.Count >= 30 Then
'Show/Hide buttons
End If
End If
End Sub
End Class
Public Class MyGroup
Public Name As String
Public Distance As Decimal
End Class
If you truly must use an array you can do something like this:
Public Class Form1
Private Ara(29) As MyGroup
Private Sub btninputdata_Click(sender As Object, e As EventArgs) Handles btninputdata.Click
If txtName.Text.Trim() <> String.Empty Then
Dim EmptyLocation = Array.FindIndex(Ara, Function(x) x Is Nothing)
If EmptyLocation > -1 Then
Ara(EmptyLocation) = New MyGroup With {.Name = txtName.Text, .Distance = txtDistance.Text}
Return
End If
'Show/Hide buttons
'Display the results however.
End If
End Sub
End Class
Public Class MyGroup
Public Name As String
Public Distance As Decimal
End Class

Reading lines from a text file in VB

I'm creating a Quiz Application in VB and the quiz app reads the questions from a text file which is already created and it has got some questions in it.
1
Q.Who won the WorldCup last time?
I Don't know
May be he knows
Who knows
Who cares?
2
Question 2
Answer A
Answer B
Answer C
Answer D
3
Question 3
Ans 1
Ans 2
Ans 3
Ans 4
The first line is the question number,the second line is the question,lines 3 - 6 represents the answer choices.Now I have created a Form for quiz and when the next button is pressed it should display the next question i.e,After the first question it should go to Question 2 and print accordingly.But unfortunately i'm unable to calculate the logic to go to next question.
Public Class Quiz
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr
End Function
Dim SCORE As Integer = 0
Dim val As Integer = 30
Dim QUES As Integer = 0
Dim Line As Integer = 1
Dim allLines As List(Of String) = New List(Of String)
Dim TextFilePath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Quiz.txt")
Private Sub Quiz_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 30
Timer1.Enabled = True
Next_Prev_Ques(Line + QUES)
End Sub
Public Function Next_Prev_Ques(quesno As Integer) As Integer
Line = quesno
Using file As New System.IO.StreamReader(TextFilePath)
Do While Not file.EndOfStream
allLines.Add(file.ReadLine())
Loop
End Using
QUES = ReadLine(Line, allLines)
Label1.Text = ReadLine(Line + 1, allLines)
RadioButton1.Text = ReadLine(Line + 2, allLines)
RadioButton2.Text = ReadLine(Line + 3, allLines)
RadioButton3.Text = ReadLine(Line + 4, allLines)
RadioButton4.Text = ReadLine(Line + 5, allLines)
Return Line
End Function
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ProgressBar1.Value += 1
val -= 1
Label2.Text = val & " Sec"
If ProgressBar1.Value = ProgressBar1.Maximum Then
Timer1.Enabled = False
End If
If ProgressBar1.Value > 25 Then
SendMessage(ProgressBar1.Handle, 1040, 2, 0)
End If
End Sub
Private Sub Quiz_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Form1.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(Line + QUES + 5)
Next_Prev_Ques(Line + QUES + 4)
Me.Refresh()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Next_Prev_Ques(Line + QUES + 5)
End Sub
The function Next_Prev_Ques Should run accordingly but its not.Can anyone post the correct code?
Below is some code that uses serialization to get the same results. You can create a class called Questions and properties on it like questionnumber, question and answer, store the data into a xml file and retrieve them with string methods. Check the code below:
The code for the class
Public Class clsQuestions
Private _Number As String
Private _Question As String
Private _Answer As String
Public Property Number() As String
Get
Number = _Number
End Get
Set(ByVal Value As String)
_Number = Value
End Set
End Property
Public Property Question() As String
Get
Question = _Question
End Get
Set(ByVal Value As String)
_Question = Value
End Set
End Property
Public Property Answer() As String
Get
Answer = _Answer
End Get
Set(ByVal Value As String)
_Answer = Value
End Set
End Property
End Class
The code for the form
Imports System.IO
Imports System.Xml.Serialization
Public Class Form1
Dim numQuestions() As String
Dim questions() As String
Dim answersGroup() As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = ""
Label2.Text = ""
Label3.Text = ""
Main()
End Sub
Private Sub Main()
Dim p As New clsQuestions
p.Number = "1,2,3,4,5,6,7,8,9,10"
p.Question = "Question 1,Question 2,Question 3," &
"Question 4,Question 5,Question 6,Question 7," &
"Question 8,Question 9,Question 10"
p.Answer = "Answer 1.1,Answer 1.2,Answer 1.3,Answer 1.4;" &
"Answer 2.1,Answer 2.2,Answer 2.3,Answer 2.4;" &
"Answer 3.1,Answer 3.2,Answer 3.3,Answer 3.4;" &
"Answer 4.1,Answer 4.2,Answer 4.3,Answer 4.4;" &
"Answer 5.1,Answer 5.2,Answer 5.3,Answer 5.4;" &
"Answer 6.1,Answer 6.2,Answer 6.3,Answer 6.4;" &
"Answer 7.1,Answer 7.2,Answer 7.3,Answer 7.4;" &
"Answer 8.1,Answer 8.2,Answer 8.3,Answer 8.4;" &
"Answer 9.1,Answer 9.2,Answer 9.3,Answer 9.4;" &
"Answer 10.1,Answer 10.2,Answer 10.3,Answer 10.4"
'Serialize object to a text file.
Dim objStreamWriter As New StreamWriter("C:\Users\Username\Documents\Questions.xml")
Dim x As New XmlSerializer(p.GetType)
x.Serialize(objStreamWriter, p)
objStreamWriter.Close()
'Deserialize text file to a new object.
Dim objStreamReader As New StreamReader("C:\Users\Username\Documents\Questions.xml")
Dim p2 As New clsQuestions
p2 = x.Deserialize(objStreamReader)
objStreamReader.Close()
numQuestions = p2.Number.Split(",")
questions = p2.Question.Split(",")
answersGroup = p2.Answer.Split(";")
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
Static x As Integer
If x <= questions.Length - 1 Then
Label1.Text = ""
Label2.Text = ""
Label3.Text = ""
arrayIndex(x)
x += 1
End If
End Sub
Private Sub arrayIndex(ByVal num As Integer)
Label1.Text = numQuestions(num)
Label2.Text = questions(num)
Dim answers() As String
answers = answersGroup(num).Split(",")
For Each item As String In answers
Label3.Text &= item & Environment.NewLine
Next
End Sub
End Class

Inventory Collection in Visual Basic

This is what the teacher is asking:
User selects an item from the list
The information about the item displays to the right (description, retail price, units)
The user enters a quantity and clicks Add to Cart
The subtotal, tax and grand total display
User clicks complete purchase button and a confirm order box appears. User clicks OK and the form clears for another transaction.
This is what I done:
Any Suggestions as of why I keep getting this error "Argument Index is not a valid value"
Imports System.IO
Public Class MainForm
Const strFILENAME As String = "Inventory.txt"
Dim dblTaxRate As Double = 8.75
Dim InventoryCollection As New Collection
Public Sub AddRecord(ByVal InvItem As Inventory)
Try
inventoryCollection.Add(InvItem, InvItem.InventoryNumber)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ClearMainForm()
txtDesc.Text = String.Empty
txtRetail.Text = ""
txtOnHand.Text = ""
txtInvNumber.Text = String.Empty
End Sub
Private Sub UpdateListBox()
lstInventory.Items.Clear()
Dim InvItem As Inventory
For Each InvItem In inventoryCollection
lstInventory.Items.Add(InvItem.InventoryNumber)
Next
If lstInventory.Items.Count > 0 Then
lstInventory.SelectedIndex = 0
Else
ClearMainForm()
End If
End Sub
Private Sub SaveRecord(ByVal objInventory As Inventory)
Dim Writer As StreamWriter
Try
Writer = File.AppendText("Inventory.txt")
Writer.WriteLine(objInventory.InventoryNumber)
Writer.WriteLine(objInventory.Description)
Writer.WriteLine(objInventory.Retail.ToString())
Writer.WriteLine(objInventory.OnHand.ToString())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim objInventory As New Inventory
Dim inventoryFile As System.IO.StreamReader
Dim blnFound As Boolean = False
Dim inventoryCollection As New Collection
Try
' Open the file.
If System.IO.File.Exists(strFILENAME) Then
End If
inventoryFile = System.IO.File.OpenText(strFILENAME)
'Enter loop and read till end of file.
Do Until inventoryFile.Peek = -1
'Read lines from file, save into Inventory object properties.
objInventory.InventoryNumber = inventoryFile.ReadLine
objInventory.Description = inventoryFile.ReadLine
objInventory.PartCost = inventoryFile.ReadLine
objInventory.Retail = inventoryFile.ReadLine
objInventory.OnHand = inventoryFile.ReadLine
'Display data in text boxes.
lstInventory.Items.Add(objInventory.InventoryNumber)
Loop
'Close the file.
inventoryFile.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DisplayInput(ByVal InvItem As Inventory)
'Display from Collection to Label boxes
Try
txtDesc.Text = InvItem.Description
txtOnHand.Text = InvItem.OnHand.ToString()
txtRetail.Text = InvItem.Retail.ToString()
txtInvNumber.Text = InvItem.InventoryNumber
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub lstInventory_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstInventory.SelectedIndexChanged
Dim objInventory As Inventory
'See if an Item is Selected
If lstInventory.SelectedIndex <> -1 Then
'Retrieve student's data from inventoryCollection. Convert object into Inventory object.
Try
objInventory = CType(inventoryCollection.Item(lstInventory.SelectedItem), Inventory)
Catch ex As Exception
'Display error message.
MessageBox.Show(ex.Message)
Console.WriteLine("")
End Try
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'Clear Form
ClearMainForm()
End Sub
Private Sub btnExits_Click(sender As Object, e As EventArgs) Handles btnExits.Click
'Close the Form
Me.Close()
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim InvID As New Inventory
InventoryCollection.Add(InvID, InvID.InventoryNumber)
End Sub
End Class
Public Class Inventory
Private StrinvNumber As String
Private strdesc As String
Private decCost As Decimal
Private decretailPrice As Decimal
Private IntqtyOnHand As Integer
'Constructor
Public Sub New()
StrinvNumber = String.Empty
strdesc = String.Empty
decCost = 0.0
decretailPrice = 0.0
IntqtyOnHand = 0.0
End Sub
Public Property InventoryNumber() As String
Get
Return StrinvNumber
End Get
Set(ByVal value As String)
StrinvNumber = value
End Set
End Property
Public Property Description() As String
Get
Return strdesc
End Get
Set(ByVal value As String)
strdesc = value
End Set
End Property
Public Property PartCost() As Decimal
Get
Return decCost
End Get
Set(ByVal value As Decimal)
decCost = value
End Set
End Property
Public Property Retail() As Decimal
Get
Return decretailPrice
End Get
Set(ByVal value As Decimal)
decretailPrice = value
End Set
End Property
Public Property OnHand() As Integer
Get
Return IntqtyOnHand
End Get
Set(ByVal value As Integer)
IntqtyOnHand = value
End Set
End Property
End Class
Presumably the issue is here:
objInventory = CType(inventoryCollection.Item(lstInventory.SelectedItem), Inventory)
Does lstInventory contain Integer values and are those values valid indexes into inventoryCollection? I would expect not. Are those two lists supposed to correspond to each other? If so then you should be using SelectedIndex rather than SelectedItem. Probably you should have just bound the list to the ListBox in the first place and then the SelectedItem would be the object you needed already.