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

Track Elapsed Time in VB.NET

Here's a very simple but effective solution for capturing elapsed time within a vb.net program.

The following sample assumes you are working within a Windows Form context. This is the "code behind" processing for some event that has been initiated within your form for which you want to capture Elapsed Time. A label "lblElapsedTime" has been created on the form and will be used to display the elapsed time value as the program runs.

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




'Two Variable declarations are needed: StartTime and ElapsedTime

dim StartTime as DateTime
dim ElapsedTime as TimeSpan

'Set the StartTime at the begin of the processing
' for which you want to capture ElapsedTime
StartTime = Now

'Begin your processing (let's assume it is some sort of looping logic)
'replace the following "For" loop with whatever
' looping construct suits your needs

For each x as integer in y

'Insert some processing here (or call to another routine)
' that will consume some time
'your code here
'Capture the Elapsed Time here as follows
ElapsedTime = Now().Subtract(StartTime)
'Now we will report the output to a Windows Form label
'display format is Hours:Minutes:Seconds
lblElapsedTime.Text = String.Format("Elapsed Time : {0:00}:{1:00}:{2:00}",_
CInt(ElapsedTime.TotalHours), _
CInt(ElapsedTime.TotalMinutes) Mod 60, _
CInt(ElapsedTime.TotalSeconds) Mod 60)
'Force the Windows Form to refresh and display the elapsed time
Me.Refresh()
Next


No comments: