How can I show a DateTimePicker dialog box, when the user pushes a button (without having to add the control to the form)
I am trying to make it so when the user pushes a button, a DateTimePicker dialog gets sho开发者_如何转开发wn, and I would even like to get the resulting date they picked. Here's what I have so far:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Dis As System.Windows.Forms.DateTimePicker = New System.Windows.Forms.DateTimePicker()
' Set the MinDate and MaxDate.
Dis.MinDate = New DateTime(1985, 6, 20)
Dis.MaxDate = DateTime.Today
' Set the CustomFormat string.
Dis.CustomFormat = "MMMM dd, yyyy - dddd"
Dis.Format = Windows.Forms.DateTimePickerFormat.Custom
' Show the CheckBox and display the control as an up-down control.
Dis.ShowCheckBox = True
Dis.ShowUpDown = True
Dis.Show()
End Sub
But when I push the button and run the code, nothing gets displayed. I would think there ought to be a way to simply display this dialog programmatically. Can anyone help me please? :-)
Just FYI, I'm coding this in VB 2010 if that helps any? :-\
In vb.net, a DateTimePicker
is not a dialog box like the OpenFileDialog, SaveFileDialog, PrintDialog
or other similar dialogs.
Despite its 'popup' appearance the DateTimePicker
is a control object, and as such it must be placed on (added to) a form or window before it can be displayed and used.
What I wound up doing, is I made a button, which opens up a separate form, which I made to look like a dialog, and put a DateTimePicker
on. That was the best workaround I could figure out how to do.
Add a form to your project and make it about the size of a calendar or date picker control. I used a calendar:
Public Class frmDatePicker
Private _Selected As Date
Public Property Selected As Date
Get
Return _Selected
End Get
Set(value As Date)
_Selected = value
End Set
End Property
Private Sub calPickDate_DateChanged(sender As Object, e As DateRangeEventArgs) Handles calPickDate.DateChanged
Selected = calPickDate.SelectionStart
End Sub
End Class
To use it:
Dim varDate As String = ""
Dim frm As frmDatePicker = New frmDatePicker()
frm.ShowDialog()
varDate = frm.Selected.ToString()
frm.Dispose()
'Do something with varDate
精彩评论