• 0

[VB.NET] Date & Time on Label


Question

Hi, I am new to VB.NET, and I have a question.

I wonder how to put current date and time on a label? I put a label (label1) on window form, and inserted following code in it:

Private Sub Label11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label11.Click
	Me.Text = Date.Now
End Sub

However, the date will be printed on window title when I click on the label.

I tried to put Label11.Text = Date.Now just under Public Class Form1, but the IDE told me to declare Label11 first.

Could someone give me some hints? Thanks very much!

Link to comment
https://www.neowin.net/forum/topic/622005-vbnet-date-time-on-label/
Share on other sites

4 answers to this question

Recommended Posts

  • 0
  Gundamdriver said:
Hi, I am new to VB.NET, and I have a question.

I wonder how to put current date and time on a label? I put a label (label1) on window form, and inserted following code in it:

Private Sub Label11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label11.Click
	Me.Text = Date.Now
End Sub

However, the date will be printed on window title when I click on the label.

I tried to put Label11.Text = Date.Now just under Public Class Form1, but the IDE told me to declare Label11 first.

Could someone give me some hints? Thanks very much!

In .NET, Me is always referring to the Form itself. Label11.Text = Date.Now() is correct, but

you have to declare a statement first (in your case a Form1.Load statement) So that when the form loads, the label has the time in it. Remember, though, the time will not change in the label afterwards, since the load statement was run and doesn't run again. If you want to keep the time updated, you can insert a Timer object which will keep the time in the label updated.

Here's your opening code:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Label1.Text = Date.Now

End Sub

Then, if you want a timer event to update the time with each passing second, you drop a Timer component onto the Form, and Enable it in the Properties sheet. Then, in the Form1_Load Event, Type the following:

Timer1.Start()

Then this as a new Timer_Tick Event (as another Subroutine, of course)

Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
		Label1.Text = Date.Now
	End Sub

Enjoy!

Edited by devHead
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.