|
-
Dec 15th, 2011, 02:56 AM
#1
Thread Starter
Member
code to input date-time using InputBox
Here is my code to input date-time using InputBox
with default date-time = today at 9 pm
I thought others might be interested or suggest improvements
vb.net Code:
Dim KeepOn As Boolean
Dim DateDefault As Date
Dim strDate As String
Dim Date1 As DateTime
Dim MyDateFmt As String = "dd/MM/yyy HH:mm:ss"
DateDefault = DateAdd("h", 21, Today())
' Today 00 hours plus 21 hours
KeepOn = True
While KeepOn
strDate = InputBox(" Enter date with format " + MyDateFmt, , _
Format(DateDefault, MyDateFmt))
Try
Date1 = DateTime.Parse(strDate)
KeepOn = False
MsgBox(" No error detected in date.parse. Proceed" _
+ Date1.ToString)
Catch ex As Exception
MessageBox.Show("Exception in Date.Parse" + _
vbNewLine + " Date string = " + strDate + _
vbNewLine + "Exception Type: " _
+ ex.GetType.ToString + _
vbNewLine + "Exception Message: " _
+ ex.Message, "Exception", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
KeepOn = True
End Try
End While
Last edited by Hack; Dec 15th, 2011 at 08:26 AM.
Reason: Added Highlight Tags
-
Dec 15th, 2011, 03:27 AM
#2
Re: code to input date-time using InputBox
My first advice would to never use InputBox and, if you want the user to enter a date and/or time, display your own dialogue with a DateTimePicker control.
Next, using Date.Parse inside a Try...Catch block is bad practice. When you don't know that the input will be valid you should be using TryParse, which doesn't throw an exception if it fails.
Finally, if you're expecting input in a specific format, as you are, then you need to enforce that format. To do that you use ParseExact in preference to Parse and TryParseExact in preference to TryParse.
The less critical issues involve getting rid of all those Runtime and using .NET standards.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|