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
Related
I need to add some controls to a Visual Basic 2017 form programmatically. One of the controls is a textbox that needs a changetext event handler. Below is some code that accomplishes that task.
HOWEVER, the changetext event handler seems to fire right away, before the form even loads... before the textbox itself even loads! A "click" handler works fine, as expected. But changetext? Nope.
I've thrown together a simplified version to demonstrate. The line with the "DIES RIGHT HERE" comment causes the problem (not the comment, but the code to the left of it).
A textbox that is added at design time will work fine, not cause this problem, but that isn't an option.
What's causing this the changetext handler to be run early? How do I work around this?
Public Class Form1
Dim txtTest As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim pntTextBox As Point
pntTextBox.X = 100
pntTextBox.Y = 100
txtTest = New TextBox
With txtTest
.Location = pntTextBox
.Width = 100
AddHandler txtTest.TextChanged, AddressOf txtTest_TextChanged
End With
Me.Controls.Add(txtTest)
End Sub
Private Sub txtTest_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyClass.TextChanged
Dim strTest As String
strTest = Str(txtTest.Width) ' ****** DIES RIGHT HERE
MsgBox(strTest)
End Sub
End Class
Made a few changes. Works.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For x As Integer = 1 To 2 'create multiple TB's
Dim pntTextBox As Point
pntTextBox.X = 100 * x
pntTextBox.Y = 100
Dim txtTest As TextBox = New TextBox
With txtTest
txtTest.Name = "tb_" & x.ToString
AddHandler txtTest.TextChanged, AddressOf txtTest_TextChanged
.Location = pntTextBox
.Width = 100
End With
Me.Controls.Add(txtTest)
Next
End Sub
Private Sub txtTest_TextChanged(ByVal sender As Object,
ByVal e As System.EventArgs) 'no handler at design time
Dim tb As TextBox = DirectCast(sender, TextBox)
Dim strTest As String
strTest = tb.TextLength.ToString
Debug.WriteLine("{0} {1}", tb.Name, strTest) 'put breakpoint here
End Sub
End Class
I am just trying to make my own VB project right now to get familiar with the language, and all I would like for it to do is continually print a string to the next line in a RichTextBox.
The issue that I can't figure out is to have it print one after another, it is printing all at once. Ill have some code down below to show where I am at right now.
I've tried using different counting methods, and depending on how it is set up, the debugger won't even load...
Friend WithEvents TableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel
Friend WithEvents Button1 As System.Windows.Forms.Button
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
End Sub
Private Sub RTB1_TextChanged(sender As System.Object, e As System.EventArgs)
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim counter1 As Integer = 0
Dim i As String = "- I" & vbCrLf
While counter1 <= 10
Timer1.Interval = 1000
Timer1.Start()
i = i + i
counter1 += 1
End While
RichTextBox1.Text = i
'Loop
'Environment.NewLine
End Sub
Friend WithEvents TableLayoutPanel2 As System.Windows.Forms.TableLayoutPanel
Private Sub TableLayoutPanel2_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles TableLayoutPanel2.Paint
End Sub
Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox
Private Sub RichTextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles RichTextBox1.TextChanged
RichTextBox1.SelectionStart = RichTextBox1.Text.Length
RichTextBox1.ScrollToCaret()
End Sub
Friend WithEvents Timer1 As System.Windows.Forms.Timer
Thank you to anyone that takes the time to look at this and help me out!
I really am looking for my output to scroll down the RichTextBox and continually to output a string on a new line over and over again one at a time.
As described:
Create a System.Windows.Forms.Timer. There are different types of Timers available. This is the one you need to update an UI component, since it's Tick event is raised in the UI thread.
Initialize the Timer and set its Interval to 1 second (1000 ms). The initialization is performed in the Shown() event of the Form, which is raised when the Form is ready to be presented (see the Docs).
Add the Timer.Tick event handler (here is added in code)
Initialize an Integer field (here, called timerCounter) which is incremented each time the Timer Ticks.
In the Tick event, add a line of text to the RichTextBox control using it's AppendText() method, which allows to add text to the control without clearing it. This method is common to all controls that inherit TextBoxBase.
Note:
I'm adding the text to the RichTextBox using an interpolated string $"{Some value}". If your version of VB.Net doesn't suppport it, use the older format:
RichTextBox1.AppendText("Line number " & timerCounter.ToString() & Environment.NewLine)
Private rtbTimer As System.Windows.Forms.Timer
Private timerCounter As Integer = 0
Protected Sub TimerTick(sender As Object, e As EventArgs)
timerCounter += 1
RichTextBox1.AppendText($"Line number {timerCounter} {Environment.NewLine}")
RichTextBox1.ScrollToCaret()
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
rtbTimer = New Windows.Forms.Timer With { .Interval = 1000 }
AddHandler rtbTimer.Tick, AddressOf TimerTick
rtbTimer.Start()
End Sub
I would like to read line by line from richtextbox and show each line every a second in label.
I have this code blocks.
and I think I need a timer but I couldnt make it.
can you help me ?
Remarks :
If I use this code , I can only see the last line in label.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim RotateCount As String()
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
Label1.Text = RichTextBox1.Lines(i)
Next
End Sub
I mean, assume that we have lines in richtextbox like..
a1
b2
c3
d4
e5
and I would like to show label1 in for each second like..
a1
(after 1 sec.)
b2
(after 1 sec.)
c3
(after 1 sec.)
like this...
You seems to expect that, because you set the Text property, the label repaints itself immediately with the new text. This doesn't happen until you exit from the event handler and the system could repaint the label. Of course, with this code, only the last text is shown.
To reach your goal, you could use a Timer set to 1 second interval and a counter that keeps track of the current line dispayed:
Dim tm As System.Windows.Forms.Timer = new System.Windows.Forms.Timer()
Dim counter As Integer = 0
At this point your button click just start the timer and exits
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
tm.Interval = 1000
AddHandler tm.Tick, AddressOf onTick
tm.Start()
' Don't allow to click again this button until
' the timer is stopped
Button1.Enabled = False
Button2.Enabled = True
End Sub
When the Tick event is raised you change the label text to the line indexed by the counter, increment it and check if you have reached the last line restarting from the first one if this is the case. Note that the button is disabled before exiting. This is required to avoid a second/third/fourth/etc click on the same button while the timer runs..... More on Button2 later....
Sub onTick(sender as Object, e as EventArgs)
Label1.Text = RichTextBox1.Lines(counter)
counter += 1
if counter >= RichTextBox1.Lines.Count Then
counter = 0
End If
End Sub
Of course, now you need another button to stop the Timer run and reenable the first button
' This button stops the timer and reenable the first button disabling
' itself - It should start as disabled from the form-designer
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
tm.Stop
RemoveHandler tm.Tick, AddressOf onTick
Button1.Enabled = True
Button2.Enabled = False
End Sub
You're almost there. Your problem is that you keep setting the text, not adding to it. Label1.Text = ... sets the text, if you want to keep adding to it you'd use Label1.Text &= ...
Also note that you need to include something like Environment.NewLine in order to include line breaks.
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
Label1.Text &= RichTextBox1.Lines(i) & If(i < RichTextBox1.Lines.Length - 1, Environment.NewLine, "")
Next
thank you for your help !!!
I solved with this code ;
Public Class Form1
Dim tm = New System.Windows.Forms.Timer()
Dim counter As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Sub onTick(sender As Object, e As EventArgs)
Label1.Text = RichTextBox1.Lines(counter)
counter += 1
If counter >= RichTextBox1.Lines.Count Then
counter = 0
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For i = 0 To RichTextBox2.Lines.Count - 1
TextBox1.Text = RichTextBox2.Lines(i)
wait(2000)
Next
End Sub
Private Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
' Allows UI to remain responsive
Application.DoEvents()
Loop
sw.Stop()
End Sub
End Class
It is very simple.
Declare one more string variable and load all string to this variable .
Improved code is given below.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As system.EventArgs) Handles Button1.Click
Dim a1 as int32
a1=0
'get number of lines of the rich text box content
a1=RichTextBox1.Lines.Count()
Dim str As String
For i As Int32 = 0 To a1-1
str = str + RichTextBox1.Lines(i)
Label1.Text= str
Next
End Sub
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?
Hey im kind of new to VB and am trying to get a web request to refresh every 30 seconds, and have got stuck on how to implement a timer in to it. Here is the code I have produced so far, i would be grateful for the correct solution:
Public Class main
Dim boatid As Integer
Sub googlemaps()
Dim url As String = "http://www.google.com"
Me.WebRequest.Navigate(New Uri(url))
'Implement timer here? (me.refresh)?
End Sub
Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectBoat.ValueChanged
boatid = SelectBoat.Value
SelectBoat.Maximum = 10
SelectBoat.Minimum = 1
Lbboatid.Text = boatid
End Sub
Private Sub btnsequence_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsequence.Click
Dim i As Integer
boatid = i
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshTimer.Tick
RefreshTimer.Enabled = True
RefreshTimer.Interval = 30000
End Sub
Private Sub main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Datetime.Text = Now.ToString
googlemaps()
End Sub
End Class
The method that has to be executed every certain period of time should be put on the
Timer1_Tick event as well. This is a small implementation try it and see if it works adapting your code accordingly:
Set up your desired Timer properties:
Click on the Timer on the Design View and on its Properties Box List set:
Interval property on 30000 (The Event will fire every 30 seconds)
Enabled on True (The Timer will start working after your form is loaded)
Then on your Codebehind
private void ShowMessage()
{
MessageBox.Show("Hello Timer");
}
private void timer1_Tick(object sender, EventArgs e)
{
ShowMessage();
}
Also here is a working implementation according to the code you posted, as for what i understand out of your code you want the browser to refresh every certain seconds as well as the numeric up and down control show the value of the variable set on boatId, this code does that:
Set the minimum and maximum properties of your numeric up down control on the Properties box of it (right click on the control in design view and search for those two properties)
Then try the following;
Public boatid As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.lblDate.Text = Now.ToString()
''Set a bigger winform to show the browser page better
Me.Width = 800
Me.Height = 600
googlemaps()
End Sub
''The browser will be refreshed every n seconds) according to what you have set on interval property of the timer control
Sub googlemaps()
Dim url As String = "http://www.google.com"
Me.WebBrowser1.Navigate(New Uri(url))
End Sub
''Loop over this method using the Tick event, while doing that verify the value
''of the boatid variable and if its less than the maximun value allowed by the numeric
''updown control increment it in one unit, then show it on the numeric selected value
''as well on the label control
Private Sub ChangeBoatIdValueCycling()
If boatid < 10 Then
boatid += 1
Else
boatid = 1
End If
Me.NumericUpDown1.Value = boatid
Me.lblBoatId.Text = boatid.ToString()
End Sub
''This wil show the id on the label text when you click up and down the numeric control
Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.lblBoatId.Text = Me.NumericUpDown1.Value.ToString()
End Sub
''This will set a variable with value 5 that will get shown selected on the numeric
''control as well as visible on the label text, the value will be shown because
''it exists in the range of 1 to 10 that is your requeriment.
Private Sub btnsequence_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsequence.Click
Dim i As Integer = 5
boatid = i
Me.NumericUpDown1.Value = boatid
Me.lblBoatId.Text = boatid.ToString()
End Sub
''Needed to repeat the form refresh and boatid cycling every n seconds according to your Interval property
''value
Private Sub RefreshTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshTimer.Tick
googlemaps()
ChangeBoatIdValueCycling()
End Sub
I hope it helps. Let me know how it goes.