How to convert string to timespan ? visual basic, stopwatch, lap system - vb.net

I am a beginer and making a stopwatch with lap feature using visual studio 2012, visual basic. Now I stuck in the lap feature. In the lap feature I want to display the result using listview ...
When the user click the lap button 2nd times it has to show the lap time between first click and 2nd click.. but i m not getting the result. Is here anybody to resolve my problem ? thank u in advance
here is the code of lap button event
Private Sub btnLap_Click(sender As Object, e As EventArgs) Handles btnLap.Click
Dim lap As String = (sw.Elapsed.Hours.ToString("00") & ":" & sw.Elapsed.Minutes.ToString("00") & _
":" & sw.Elapsed.Seconds.ToString("00") & ":" & sw.Elapsed.Milliseconds.ToString("00"))
lapcount += 1
Dim i As Integer = ListView1.Items.Count
If i <= 0 Then
ListView1.Items.Add(CStr(lapcount), i)
ListView1.Items(i).SubItems.Add(lap)
ListView1.Items(i).SubItems.Add(lap)
Else
ListView1.Items.Add(CStr(lapcount), i)
ListView1.Items(i).SubItems.Add(lap)
ListView1.Items(i).SubItems.Add((TimeSpan.parse(lap)- Timespan.parse(lastlap)).ToString) ''' I can't subtract the value from 2nd click to first click
End If
lastlap = (ListView1.Items(i).SubItems(1).ToString)
End Sub

To be honest, its usually a bad idea to use UI objects as your primary store of data. You would be much better storing the split times in a List (Of TimeSpan) and calculating calculating the lap times from that.
In my sample I declared some class objects so that the code would run. You could adapt these as necessary.
Dim sw As New Stopwatch
Dim lapcount As Integer = 1
Dim lastlap As Integer
Dim lapintervals As New List(Of TimeSpan)
Dim timeFormat As String = "hh\:mm\:ss\.fff"
So in your button click event you would have something like this ..
Private Sub BtnLap_Click(sender As Object, e As EventArgs) Handles BtnLap.Click
Dim ts As TimeSpan = sw.Elapsed
lapintervals.Add(ts)
AddTimeToListView(lapintervals.Count, lapintervals.Last)
lapcount += 1
End Sub
And you would add the info to your ListView like this
Private Sub AddTimeToListView(lapcount As Integer, lapsplit As TimeSpan)
Dim lvItem As New ListViewItem(lapcount.ToString, lapcount)
If lapcount = 1 Then
lvItem.SubItems.Add(lapsplit.ToString(timeFormat))
lvItem.SubItems.Add(lapsplit.ToString(timeFormat))
Else
lvItem.SubItems.Add(lapsplit.ToString(timeFormat))
lvItem.SubItems.Add((lapsplit.Subtract(lapintervals(lapcount - 2))).ToString(timeFormat))
End If
ListView1.Items.Add(lvItem)
End Sub

thenk you very much for answering...
finally i have finished my stopwatch application ..
i've made this and my leader gave me 8 out of 10 .. it pretty much good for me
here is the design form and code
visual basic 2012, stopwatch with lap button
enter image description here
[code]
Public Class Stopwatch
Public watch As Form 'スタートページから呼び出すため
Dim sw As New System.Diagnostics.Stopwatch()
Dim lapcount As Integer
Dim lastlap As String
'スタート・ストップボタン
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
If btnStart.Text = "Start" Then
sw.Start() '時間計測開始
Timer1.Interval = 10
Timer1.Enabled = True
btnStart.Text = "Stop"
Else
sw.Stop() '時間計測一時停止
Timer1.Enabled = False
btnStart.Text = "Start"
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
lblTime.Text = sw.Elapsed.ToString("hh\:mm\:ss\:ff")
End Sub
'cancel / reset ボタン
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
sw.Reset() '初期状態にする
Timer1.Enabled = False
lblTime.Text = "00:00:00:00"
ListView1.Items.Clear()
btnStart.Text = "Start"
lapcount = 0
End Sub
'ラップボタン
Private Sub btnLap_Click(sender As Object, e As EventArgs) Handles btnLap.Click
Dim lap = sw.Elapsed.ToString("hh\:mm\:ss\:fff") ' ラップ時間を変数に代入
lapcount += 1
Dim i As Integer = ListView1.Items.Count
If i <= 0 Then ' ListviewのアイテムのValueが0または0より小さければ
ListView1.Items.Add(CStr(lapcount), i)
ListView1.Items(i).SubItems.Add(lap) 'アイテムとサブアイテム表示
ListView1.Items(i).SubItems.Add(lap)
Else '文字列となっている結果時間を整数型に変換する/ // ラップ経過時間を取得するため
Dim day As Integer = 0
Dim hr As Integer = CInt(Strings.Left(lap, 2))
Dim min As Integer = CInt(Strings.Mid(lap, 4, 2))
Dim sec As Integer = CInt(Strings.Mid(lap, 7, 2))
Dim milli As Integer = CInt(Strings.Mid(lap, 10, 3))
Dim dayy As Integer = 0
Dim hrr As Integer = CInt(Strings.Mid(lastlap, 19, 2))
Dim minn As Integer = CInt(Strings.Mid(lastlap, 22, 2))
Dim secc As Integer = CInt(Strings.Mid(lastlap, 25, 2))
Dim millii As Integer = CInt(Strings.Mid(lastlap, 28, 3))
'現在のラップ時間に直前に記憶したラップ時間を引き、1回目から2回目のラップボタン押下までの経過時間を図る
Dim answer = createtimespan(day, hr, min, sec, milli) - createtimespan(dayy, hrr, minn, secc, millii)
Dim ansTS = answer.ToString("hh\:mm\:ss\:fff") 'ミリ秒3桁まで表示するように指定
ListView1.Items.Add(CStr(lapcount), i)
ListView1.Items(i).SubItems.Add(lap)
ListView1.Items(i).SubItems.Add((ansTS).ToString) 'ラップ時間の表示
End If
lastlap = ListView1.Items(i).SubItems(1).ToString '直前のラップタイムを記憶
End Sub
Private Function createtimespan(ByVal days As Integer, ByVal hours As Integer, ByVal minutes As Integer, _
ByVal seconds As Integer, ByVal milliseconds As Integer) As TimeSpan
Dim elapsedTime As New TimeSpan(days, hours, minutes, seconds, milliseconds)
Return (elapsedTime)
End Function
End Class

Related

index was outside the bounds

my code is not working please, help
Private Sub Form3_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
Dim lblControls() As Label = {lblName, lblID, lblGender, lblBirthDate, lblCity, lblContactNumber, lblAddress, lblHistory}
Dim sReader As New System.IO.StreamReader(Form1.pathStorage & "Patients\" & selectedPatient & "\patientInfo.txt")
Dim strValues(11) As String
Dim counter As Integer = 0
While sReader.Peek <> 1
strValues(counter) = sReader.ReadLine
counter += 1
End While
counter = 0
For Each lbl As Label In lblControls
lbl.Text = strValues(counter)
counter += 1
Next
sReader.Close()
I have changed to the File class to accomplish your task. You do not need to declare an instance of File. A StreamReader needs to be not closed but disposed. A Using...End Using block or Try...Finally...End Try to ensure the closing and disposing of a StreamReader so the File class is easier to use.
You do not need to declare a size for the strValues because it is initialize at declaration. I added a check that the two arrays are the same size.
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
Dim lblControls() As Label = {lblName, lblID, lblGender, lblBirthDate, lblCity, lblContactNumber, lblAddress, lblHistory}
Dim path As String = pathStorage & "Patients\" & selectedPatient & "\patientInfo.txt"
Dim strValues = File.ReadAllLines(path) 'Returns a string array
If lblControls.Length <> strValues.Length Then
MessageBox.Show("Labels do not equal data.")
Return
End If
Dim counter As Integer = 0
For Each lbl As Label In lblControls
lbl.Text = strValues(counter)
counter += 1
Next
End Sub

Fibonacci Sequence Visual Basic

I have a quick question about another Visual Basic assignment I'm working on. I have all the code and everything has gone smoothly so far. The app is meant to display the first 100 Fibonacci numbers in a list box, adding the two previously displayed numbers to get the next in a loop. The only problem is that when I hit the button to display the code, the loop continues, and doesn't just stop at 100 numbers. Where did I go wrong?
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim dblA As Double = 0
Dim dblB As Double = 1
Dim dblC As Double
Dim intCounter As Integer
lstSequence.Items.Add(dblA.ToString)
lstSequence.Items.Add(dblB.ToString)
For intCounter = 1 To 100
dblC = dblA + dblB
dblA = dblB
dblB = dblC
lstSequence.Items.Add(dblC.ToString)
Next
End Sub
I just tried this. It works fine.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim a As Integer = 0
Dim b As Integer = 1
Dim fib As Integer
Dim userinput, i As Integer
userinput = InputBox("how many interations?")
i = userinput
ListView1.Items.Add(1)
Do
fib = a + b
a = b
b = fib
ListView1.Items.Add(fib)
i = i + 1
Loop While fib < i
End Sub
End Class

My counter adds 1 but doesn't update properly

This is a slot machine program. I am trying to detect how many times the user clicks a button (spins). But I can't figure out why my counter only adding 1 to my clickLabel? I'm sure it's a simple fix but I'm drawing a blank.
Public Class MainForm
Private Sub clickHereButton_Click(sender As Object, e As EventArgs) Handles clickHereButton.Click
' simulates a slot machine
Dim randGen As New Random
Dim leftIndex As Integer
Dim centerIndex As Integer
Dim rightIndex As Integer
Dim counter As Integer = 1
clickHereButton.Enabled = False
For spins As Integer = 1 To 10
leftIndex = randGen.Next(0, 6)
leftPictureBox.Image = ImageList1.Images.Item(leftIndex)
Me.Refresh()
System.Threading.Thread.Sleep(50)
centerIndex = randGen.Next(0, 6)
centerPictureBox.Image = ImageList1.Images.Item(centerIndex)
Me.Refresh()
System.Threading.Thread.Sleep(50)
rightIndex = randGen.Next(0, 6)
rightPictureBox.Image = ImageList1.Images.Item(rightIndex)
Me.Refresh()
System.Threading.Thread.Sleep(50)
Next spins
If leftIndex = centerIndex AndAlso
leftIndex = rightIndex Then
MessageBox.Show("Congratulations!", "Winner", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
counter += 1
clickLabel.Text = counter.ToString()
clickHereButton.Enabled = True
clickHereButton.Focus()
End Sub
Private Sub exitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
Me.Close()
End Sub
End Class
What's happening is you're always setting the counter to 1 everytime you click the button because it is inside the clickHereButton_Click. So even though you are incrementing it, at the beginning of your sub you are still setting it to 1.
Dim counter As Integer = 1
Private Sub clickHereButton_Click(sender As Object, e As EventArgs) Handles clickHereButton.Click
...
End Sub

Score not being calculated correctly

Hi I'm created a program for a project and I've now started running some tests and the score for the user isn't being calculated correctly and I believe that it can't compare the answer given to the correct answer. I'm very confused and need any help that can be given. My code looks like this, any confusing parts and I'll try and explain.
Imports System.IO
Public Class QuestionScreen
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Main.Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Main.Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i As Integer = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
If Ans_TxtBx.Text = answers(i) Then
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class
OK..... Try this, I have debugged your code trying to leave it pretty much as you had it, there were a number of problems, nothing major just a few lines of code in the wrong place....
Imports System.IO
Public Class Form1
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Try
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
' clear the list of questions and answers
answers.Clear()
questions.Clear()
'''''''''''''''''''''''''''''''''''''''''
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
Catch ex As Exception
End Try
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
Call ReadFile() ' move this to the bottom
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
count = count + 1
If Ans_TxtBx.Text = answers(i - 1) Then ' need to subtract 1 here
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
Call ReadFile() ' move this to the bottom
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class

Make specific randomly generated codes with timer

I would like to make randomly generated codes when a timer is finished.
But I would like to use this code ABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789
on this format XXXX-XXXX-XXXX (replace X with a randomly generated number/letter)
And I would like to insert the code in this
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ProgressBar1.Increment(3)
If ProgressBar1.Value = 100 Then
TextBox1.Text = "replace textbox by code"
Timer1.Stop()
End If
End Sub
Here's a solution using LINQ.
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ProgressBar1.Increment(3)
If ProgressBar1.Value = 100 Then
Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim random = New Random()
Dim num1 = New String(Enumerable.Repeat(chars, 4).Select(Function(s) s(random.Next(s.Length))).ToArray())
Dim num2 = New String(Enumerable.Repeat(chars, 4).Select(Function(s) s(random.Next(s.Length))).ToArray())
Dim num3 = New String(Enumerable.Repeat(chars, 4).Select(Function(s) s(random.Next(s.Length))).ToArray())
Dim result = num1 & "-" & num2 & "-" & num3
TextBox1.Text = result
Timer1.Stop()
End If
End Sub
With this, you'd just change your TextBox1.Text = to point to the getNewRandomString() function.
Private Function getNewRandomString() As String
Dim sb As New StringBuilder
For i = 1 To 3
For j = 1 To 4
sb.Append(getNewRandomLetter())
Next
sb.Append("-")
Next
Return sb.ToString.Trim("-")
End Function
Private Function getNewRandomLetter() As Char
Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Return (chars(GetRandom(0, chars.Length - 1)))
End Function
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
Static Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max + 1)
End Function