vb.net Tips & Tricks

Need a snippet of vb.net code to perform a particular programming task? Most coders (like the author of this Blog) don't keep every coding trick they've learned stored in their head - they figure out a solution once and refer back to previous programs when they need to use it again. Check here for (hopefully) useful chunks of code to reduce your programming efforts.

Is vb.net too limited for you?
Need a scripting environment that won't hold you back?

If so, move up to Windows PowerShell and check out some useful tips here: http://poshtips.com

Digital Clock/Calendar

I found that the built-in clock on my Windows Mobile phone was a bit small and difficult to read with my tired old eyes, so I whipped up this quick application to remedy the situation. It will display the current time, date, and day of week. You can use this on a Windows Mobile application or a regular Windows form application. To make it all work, you will need three labels and a timer control added to your form.

Drag three label controls onto your form and name them as follows:
lblClock
lblDate
lblDay

Next, drag a timer control to the form (I just kept the default "Timer1" name)
Timer1

Now you just need update the label size, font, color, etc to your liking and you're ready to insert the code.

Here's the whole program, start to finish. Pretty simple, but it gets the job done.

Environment: VB.NET, Visual Studio 2005, .NET 2.0




Public Class Form1

Public hr, mn, se As Integer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
hr = 0
mn = 0
se = 0
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

Dim ts As Date = Now
lblClock.Text = String.Format("{0:D2}:{1:D2}:{2:D2} {3}", ts.Hour Mod 12, ts.Minute, ts.Second, GetXM(ts))
lblDate.Text = String.Format("{0:D2}/{1:D2}/{2:D4}", ts.Month, ts.Day, ts.Year)
lblDay.Text = ts.DayOfWeek.ToString
End Sub

Private Function GetXM(ByVal ts As Date) As String
If ts.Hour >= 12 Then
Return "PM"
Else
Return "AM"
End If
End Function
End Class


No comments: