Conversion of time to seconds - vb.net

I have this conversion issue.
I have a stopwatch which counts down. Then displays it on a label so it shows like this "15:00:00" on a label(label1) counting down.
I have another time which loop every 10 seconds to lap the stopwatch and save the lapped time to another label(label2)
So how did I get 15:00:00?
I have 3 textboxes in my form, 1st is for hours, 2nd for minutes and third for sec.
If I input 15 on hours, and 00 on minutes and seconds and hit button1, it automatically converts 15hours(15:00:00) to seconds which is saved in my database so instead of saving 15:00:00 it saves the TotalSeconds which is 54000 Seconds.
When my stopwatch starts, it gets the 54000 from database and again converts it to 15:00:00 that is displayed in label1.
Can I convert lapped time on label2("13:00:00") to seconds which will display the converted value yet to another label(which is now label3).?
Imports System
Imports System.Timers
Public Class ClientDashboard
Dim StopWatch As New Stopwatch
Dim CountDown As TimeSpan
Dim IsRunning As Boolean = False
Private Shared timer As System.Timers.Timer
Private Sub ClientDashboard_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Sets dashboard to right
Me.Size = New System.Drawing.Size(317, 900)
Dim x As Integer
Dim y As Integer
x = Screen.PrimaryScreen.WorkingArea.Width - 317
y = Screen.PrimaryScreen.WorkingArea.Height - Screen.PrimaryScreen.WorkingArea.Height
Me.Location = New Point(x, y)
'get time of user
cn = New ADODB.Connection
Call conDB()
cn.Open()
Dim rs As New ADODB.Recordset
rs.Open("select * from tb_registration where=st_acc_number= '" & id_lbl.Text & "'", cn, 0, 3)
iduser_lbl.Text = "'" & rs("st_name").Value & "'""'" & rs("st_lname").Value & "'"
UserTotal.Text = rs("st_totaltimeleft").Value
'Start stopwatch
StopWatch.Start()
synchroUpdate.Enabled = True
synchroUpdate.Start()
Dim numSecs As Integer
Integer.TryParse(UserTotal.Text, numSecs)
CountDown = TimeSpan.FromSeconds(numSecs)
End Sub
Private Sub synchro_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles synchro.Tick
End Sub
'--------------------->>>> Methord 2 <<<<----------------------
Private Sub DispElaps(ByVal ts As TimeSpan, ByVal lbl As Label)
lbl.Text = String.Format("{0:00} : {1:00} : {2:00}", _
Math.Floor(ts.TotalHours), _
ts.Minutes, _
ts.Seconds, _
ts.Milliseconds)
End Sub
Private Sub synchroUpdate_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles synchroUpdate.Tick
synchroUpdate.Interval = 100
'If countDown > stpw.Elapsed Then
Dim elaps As TimeSpan = CountDown - StopWatch.Elapsed
DispElaps(elaps, TimerOutput)
'Else
'End If
End Sub
Private Sub DoEvent()
timer = New System.Timers.Timer(5000)
AddHandler timer.Elapsed, AddressOf AC
timer.AutoReset = True
timer.Enabled = True
End Sub
'Address of event
Private Sub SaveEvent2(ByVal sender As System.Object, ByVal e As EventArgs)
AutoUpdate_Button.PerformClick()
End Sub
'Event Handler
Private Sub AC()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf AC))
Else
Me.AutoUpdate_Button.PerformClick()
End If
End Sub
Private Sub logoutBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles logoutBTN.Click
End Sub
End Sub
End Class

Your code seems to use good names for labels, but your question has not been updated to correspond.
Nevertheless, can you just use TimeSpan.TotalSeconds similar to where where you're already using TimeSpan.TotalHours?

Related

Adding Conditions to the Listboxes from .csv files

enter image description herei am looking for this problem for very long time and I have found nothing about that... :( .
So, I have 2 .csv files. In the .csv file 1 are the listboxes and all of these listboxes have one number between 1 and 6. In the .csv file 2 are some tools like (audi, bmw) and the tools have one numer between 1 and 6 too.
Example:
.csv file 1
Listbox 1 (X,Y,Length,Width) category 1
Listbox 2 (X,Y,Length,Width) category 2
Listbox 3 (X,Y,Length,Width) category 3
.csv file 2
Mercedes category 1
BMW category 2
Audi category 3
So, I want compare the 2 .csv files and allow the listbox 2 for only BMW to drag and drop.
If I drop categroy 2 to category 1 in the listbox, it should be false.
Imports System.Windows.Forms
Imports System.IO
Public Class Form2
Private meineListBoxen As New List(Of ListBox)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim strZeilen() As String
Dim strFelder() As String
Dim strZeilen0() As String
Dim strZeilen2() As String = IO.File.ReadAllLines("K:\Ruebel_Andreas\Modellpflege\Datenerfassung.csv")
Dim strFelder1() As String
strZeilen = File.ReadAllLines("K:\Ruebel_Andreas\Modellpflege\listboxpflege.csv")
strZeilen0 = IO.File.ReadAllLines("K:\Ruebel_Andreas\Modellpflege\Spritzguss.csv")
For i As Integer = 1 To strZeilen.GetUpperBound(0)
strFelder = strZeilen(i).Split(";")
meineListBoxen.Add(New ListBox)
With meineListBoxen(i - 1)
.Left = strFelder(0)
.Top = strFelder(1)
.Width = strFelder(2)
.Height = strFelder(3)
End With
Me.Controls.Add(meineListBoxen(i - 1))
Me.meineListBoxen(i - 1).AllowDrop = True
AddHandler meineListBoxen(i - 1).MouseDown, AddressOf meineListbox_MouseDown
AddHandler meineListBoxen(i - 1).DragDrop, AddressOf meineListbox_DragDrop
AddHandler meineListBoxen(i - 1).DragEnter, AddressOf meineListbox_DragEnter
Next
For a As Integer = 0 To strZeilen0.GetUpperBound(0)
Me.meineListBoxen(1 - 1).Items.Add(strZeilen0(a).Substring(0, strZeilen0(a).IndexOf(";")))
Next
For j As Integer = 1 To strZeilen2.GetUpperBound(0)
strFelder1 = strZeilen2(j).Split(" ")
With meineListBoxen(j)
.Items.Add(strFelder1(4))
End With
For Each itm In meineListBoxen(j).Items
If meineListBoxen(1 - 1).Items.Contains(itm) Then meineListBoxen(1 - 1).Items.Remove(itm)
Next
Next
End Sub
Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
Me.lblMaus.Text = "X: " & e.X & " , Y:" & e.Y
End Sub
Private source As ListBox
Private sourceIndex As Integer
Private Sub meineListbox_MouseDown(ByVal sendre As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Dim aPoint As Point
Dim lbx As ListBox
Dim aIndex As Integer
lbx = CType(sendre, ListBox)
aPoint = New Point(e.X, e.Y)
aIndex = lbx.IndexFromPoint(aPoint)
Try
If aIndex <= 0 Then
source = lbx
sourceIndex = aIndex
lbx.DoDragDrop(lbx.Items(aIndex), DragDropEffects.All)
End If
Catch ex As Exception
MessageBox.Show("Bitte wählen Sie ein Werkzeug aus")
End Try
End Sub
Private Sub meineListbox_DragDrop(ByVal sender As System.Object,
ByVal e As System.Windows.Forms.DragEventArgs)
Dim lbx As ListBox
lbx = CType(sender, ListBox)
If Not source Is Nothing Then
source.Items.RemoveAt(sourceIndex)
End If
lbx.Items.Add(e.Data.GetData(DataFormats.Text))
End Sub
Private Sub meineListbox_DragEnter(ByVal sender As System.Object,
ByVal e As System.Windows.Forms.DragEventArgs)
If (e.Data.GetDataPresent(DataFormats.Text)) Then
e.Effect = DragDropEffects.All
Else
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub cmdSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Speichern.Click
Dim w As New IO.StreamWriter("K:\Ruebel_Andreas\Modellpflege\Datenerfassung.csv")
For i = 0 To meineListBoxen.Count - 1
w.WriteLine(meineListBoxen.Item(i))
Next
w.Close()
End Sub
Private Sub WerkzeugHinzufügen_Click(sender As Object, e As EventArgs) Handles WerkzeugHinzufügen.Click
Process.Start("K:\Ruebel_Andreas\Modellpflege\Spritzguss.csv")
End Sub
Private Sub StellplatzHinzufügen_Click(sender As Object, e As EventArgs) Handles StellplatzHinzufügen.Click
Process.Start("K:\Ruebel_Andreas\Modellpflege\listboxpflege.csv")
End Sub
End Class
Private Sub cmdSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Speichern.Click
Using w As New StreamWriter("K:\Ruebel_Andreas\Modellpflege\Datenerfassung.csv")
For i = 0 To meineListBoxen.Count - 1
w.WriteLine(meineListBoxen.Item(i))
Next
End Using
End Sub
I find it odd that the Handles clause does not match the name of the method. The default would be Private Sub Speichern_Click
StreamWriter needs to be disposed. Using...End Using blocks will handle this even if there is an error.
Let's say you have 3 list boxes. Your loop will go from index 0 to index 2. WriteLine will call ToString on each item in the list of ListBox. I don't believe that a ListBox provides an implementation of ToString so you will get the fully qualified name of the object's type. I don't think you want this.
Private Sub cmdSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Speichern.Click
Using w As New StreamWriter("K:\Ruebel_Andreas\Modellpflege\Datenerfassung.csv")
For Each LB As ListBox In meineListBoxen
For Each item As String In LB.Items
w.WriteLine(item)
Next
Next
End Using
End Sub
You can initialize your variables as you declare them and with Option Infer they will be strongly typed (only works for local variables.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim strZeilen2 = File.ReadAllLines("K:\Ruebel_Andreas\Modellpflege\Datenerfassung.csv")
Dim strZeilen = File.ReadAllLines("K:\Ruebel_Andreas\Modellpflege\listboxpflege.csv")
Dim strZeilen0 = File.ReadAllLines("K:\Ruebel_Andreas\Modellpflege\Spritzguss.csv")
For i = 1 To strZeilen.GetUpperBound(0) 'Why are skipping the first line?
Dim strFelder = strZeilen(i).Split(";"c)
Dim LB As New ListBox
With LB
.Left = CInt(strFelder(0))
.Top = CInt(strFelder(1))
.Width = CInt(strFelder(2))
.Height = CInt(strFelder(3))
.AllowDrop = True
.Name = "ListBox" & i 'In case you need to refer to the control be name
End With
If i = 1 Then
For a As Integer = 0 To strZeilen0.GetUpperBound(0)
LB.Items.Add(strZeilen0(a).Substring(0, strZeilen0(a).IndexOf(";")))
Next
End If
AddHandler LB.MouseDown, AddressOf meineListbox_MouseDown
AddHandler LB.DragDrop, AddressOf meineListbox_DragDrop
AddHandler LB.DragEnter, AddressOf meineListbox_DragEnter
'I fleshed out the control before adding to the collections
Controls.Add(LB)
meineListBoxen.Add(LB)
Next
For j = 1 To strZeilen2.GetUpperBound(0) 'Again skipping first line, perhaps it is a title line
Dim strFelder1 = strZeilen2(j).Split(" "c)
meineListBoxen(j).Items.Add(strFelder1(4)) 'You are skipping the first list box
For Each itm In meineListBoxen(j).Items
If meineListBoxen(0).Items.Contains(itm) Then
meineListBoxen(0).Items.Remove(itm)
End If
Next
Next
End Sub
No need to define a point, just pass the coordinates to the IndexFromPoint method. You can use DirectCast to get the ListBox since we are sure the sender is a ListBox. DirectCast skips some of the checks that CType does so the method so is a bit faster. I am not sure if the check on the value of aIndex is necessary. Exception handling is heavy and shouldn't be used for a simple value check.
Private Sub meineListbox_MouseDown(sender As System.Object, e As System.Windows.Forms.MouseEventArgs)
Dim lbx = DirectCast(sender, ListBox)
Dim aIndex = lbx.IndexFromPoint(e.X, e.Y)
If aIndex < 0 Then
MessageBox.Show("Bitte wählen Sie ein Werkzeug aus")
Else
source = lbx
sourceIndex = aIndex
lbx.DoDragDrop(lbx.Items(aIndex), DragDropEffects.All)
End If
End Sub
Use IsNot when checking for null objects.
Private Sub meineListbox_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs)
Dim lbx = DirectCast(sender, ListBox)
If source IsNot Nothing Then
source.Items.RemoveAt(sourceIndex)
End If
lbx.Items.Add(e.Data.GetData(DataFormats.Text))
End Sub
Updating this label over and over will just slow things down. Delete this Sub.
'Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
'lblMaus.Text = "X: " & e.X & " , Y: " & e.Y
'End Sub
I can't help more without correct data from your files. At one point, you are splitting by a semicolon and there aren't any in your sample data! The file content you showed is certainly not a CSV file.

Visual Basic - Start process or tasks after a specific delay

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Process.Start("https://google.com/")
'I want to wait here for 20 seconds. Then I want him to open the yandex.
Process.Start("https://yandex.com/")
End Sub
Can you help me how can I do. Thanks for all.
In this example you can see how start a process after a specific delay.
In your case is launch a browser but you can use in other scenarios as a technique delay related.
Take a look on code and improve it based in your necessities.
Event TimerDone()
Private Sub ProcessStartAfterDelay(Optional ByVal url As String = "", Optional interval As Integer = 2000)
Dim tmr As System.Windows.Forms.Timer = New System.Windows.Forms.Timer
AddHandler tmr.Tick, Sub()
tmr.Stop()
tmr.Dispose()
If url.Length > 0 Then
Try
Process.Start(url)
RaiseEvent TimerDone()
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
End If
End Sub
tmr.Interval = interval
tmr.Start()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim index As Integer = 0
Dim delay As Integer = 3000
Dim listOfUrls As List(Of String) = New List(Of String)({"https://google.com/",
"https://yandex.com/",
"https://it.yahoo.com/",
"https://www.wikipedia.org/"})
' First launch need to be here with delay > 0 important!
ProcessStartAfterDelay(listOfUrls(index), 1)
AddHandler Me.TimerDone, Sub()
index += 1
If index < listOfUrls.Count Then
ProcessStartAfterDelay(listOfUrls(index), delay)
Else
RemoveHandler Me.TimerDone, Nothing
End If
End Sub
End Sub

Refreshing text in a TextBox at intervals of 1 second

I am attempting to display the local time in a text box but have it refresh... I used a timer to hopefully refresh the time, but it does not seem to reprint my text. If you could take the time to help me out that would be great!
EDIT*** So I attempted this with TextBox.AppendText() to see what happens if it continually reprints and I noticed that the date and time does not update at all. Do I need to refresh the form???
Public Class Form1
Dim t As String = My.Computer.Clock.LocalTime
Dim m As String = t & vbCrLf & " - Time Left - "
Private Timer As System.Windows.Forms.Timer
Private TimerCounter As Integer = 0
Dim TempText As String = m
Protected Sub TimerTick(ByVal sender As Object, ByVal e As EventArgs)
TextBox.TextAlign = HorizontalAlignment.Center
TimerCounter += 1
TextBox.Text = t
End Sub
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Shown 'this goes with the line just above
Timer = New Windows.Forms.Timer With {.Interval = 1000}
AddHandler Timer.Tick, AddressOf TimerTick
Timer.Start()
End Sub
End Class
My expected result if for the local time to update in the textbox1 each time the timer ticks.
You set the variable t at the moment of its declaration, but then you never update it. So it contains always the same value.
In reality you don't even need that variable. You can set simply the TextBox.Text to the My.Computer.Clock.LocalTime
Protected Sub TimerTick(ByVal sender As Object, ByVal e As EventArgs)
' You can set this property just one time when you define your TextBox
' TextBox.TextAlign = HorizontalAlignment.Center
TimerCounter += 1
TextBox.Text = My.Computer.Clock.LocalTime
End Sub

Create timers dynamically and add unique names VB.net

Alright,
I know how to create buttons and give them each unique names to access them
I do it like this
Dim btnName As String
Dim x As Short
For i As Short = 1 To 3
btnName = "button" & CStr(i)
x += 3
Dim button1 As New Button
button1.Name = btnName
Me.Controls.Add(button1)
button1.Location = New Point(10, x * 10)
button1.Text = "Hello" & i
Next
When I try to create a timer, I cannot give it a name like I did above with the buttons
btnName = "button" & CStr(i)
button1.Name = btnName
So I don't know how to access them and/or activate them for instance. I want to create like three timers and name them like "timer1", "timer2", "timer3"
How do I achieve that?
'Here Is a form code that starts a timer on a button click
Public Class Form1
Dim t1 As Timer
Dim t2 As Timer
Dim t3 As Timer
Private Sub btnT1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnT1.Click
'on btn click start timer1
t1 = New Timer
t1.Tag = DateTime.Now
AddHandler t1.Tick, AddressOf MyTickHandler
t1.Start()
End Sub
Private Sub btnT2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnT2.Click
'on btn click start timer2
t2 = New Timer
t2.Tag = DateTime.Now
AddHandler t2.Tick, AddressOf MyTickHandler
t2.Start()
End Sub
Private Sub btnT2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnT3.Click
'on btn click start timer3
t3 = New Timer
t3.Tag = DateTime.Now
AddHandler t3.Tick, AddressOf MyTickHandler
t3.Start()
End Sub
Sub MyTickHandler(ByVal sender As Object, ByVal e As EventArgs)
dim t As Timer = DirectCast(sender, Timer)
dim timerString = "The timer started at " & t.Tag.ToString & " just ticked..."
End Sub
Private Sub btnStopT1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopT1.Click
'stop timer1
t1.Stop()
t1.Dispose()
End Sub
Private Sub btnStopT2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopT2.Click
'stop timer 2
t2.Stop()
t2.Dispose()
End Sub
Private Sub btnStopT3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopT3.Click
'stop timer 3
t3.Stop()
t3.Dispose()
End Sub
End Class
Timer Class
This tutorial should help you create a timer object.
Tutorial 2: Create a Timed Math Quiz
Tutorial link
In detail step 3 will do the trick.
Step 3: Add a Countdown Timer
Link to step 3
This piece of shows how you can do something with the tick event (copy from the MSDN site)
Private Sub Timer1_Tick() Handles Timer1.Tick
If timeLeft > 0 Then
' Display the new time left
' by updating the Time Left label.
timeLeft -= 1
timeLabel.Text = timeLeft & " seconds"
Else
' If the user ran out of time, stop the timer, show
' a MessageBox, and fill in the answers.
Timer1.Stop()
timeLabel.Text = "Time's up!"
MessageBox.Show("You didn't finish in time.", "Sorry!")
sum.Value = addend1 + addend2
startButton.Enabled = True
End If

Timer Inside Label

I am trying to put a countdown timer insde my label in my program, but when I run the program it doesn't countdown. It skips right to one, and that's it.
Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick
Dim Time As Integer = 11
Do Until Time = 0
ClockLabel.Text = "Compacting database in: " & Time
Time -= 1
Loop
End Sub
I also have started the timer and declared the interval to 500 in the Form_Load routuine.
Get rid of the loop and declare the Time variable outside the scope.
Dim Time As Integer = 11
Private Sub CompactTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
Handles CompactTimer.Tick
If Time >= 0 Then
ClockLabel.Text = "Compacting database in: " & Time
Time -= 1
Else
CompactTimer.Stop
End If
End Sub
make a static var ..
Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick
Static Time As Integer = 11
ClockLabel.Text = "Compacting database in: " & Time
Time -= 1
If Time = 0 Then CompactTimer.Stop
End Sub
The loop happens each time the timer ticks. You most likely want something like:
Dim time as Integer = 11 ' Declare outside
Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick
If Time = 0 Then
CompactTimer.Enabled = False ' Disable timer
ClockLabel.Text = "Compacting database now"
Else
ClockLabel.Text = "Compacting database in: " & time
time -= 1
End If
End Sub
If you want the code to show the actual amount of time then the code could look like this.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'start the count down
CompactTimer.Interval = 500
CompactTimer.Start()
stpw.Stop()
stpw.Reset()
stpw.Restart()
End Sub
Dim stpw As New Stopwatch
Dim countdown As New TimeSpan(0, 0, 11) 'length of countdown in seconds
Private Sub CompactTimer_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CompactTimer.Tick
Dim togo As TimeSpan = countdown - stpw.Elapsed
If togo.TotalSeconds > 0 Then
ClockLabel.Text = String.Format("Compacting database in: {0} secs.", togo.TotalSeconds.ToString("n0"))
Else
CompactTimer.Stop()
End If
End Sub
Relying on the interval to mark the passing of time will result in inaccuracy.