我想从VB中的DateTimePicker中获取选定的值(如果我只选择日期值,那么我只希望获得选定的日期值.)
在此图像中,我从此DateTimePicker中选择了(蓝色标记的)年份值.所以我只需要今年的价值.
在TextBox的情况下,我可以使用选择的值
TextEndTime.SelectedText
由于可以使用箭头键操作DateTimePicker控件,因此可以使用SendKeys更改当前选定的值.
以下示例获取DateTimePicker的当前DateTime值,并在发送↑键后将值与新值进行比较.最后,它将DateTimePicker重置为原始值.
所以变量currSelected将包含最后一个Selection.
Dim currVal As DateTime Dim newVal As DateTime Dim valCheck As Boolean Dim currSelected As Selection = Selection.None Public Enum Selection None = 0 Year = 1 Month = 2 Day = 3 End Enum Private Sub CheckDTPSelection(dtp As DateTimePicker) valCheck = True currVal = dtp.Value SendKeys.Send("{UP}") End Sub Sub RefreshSelection(dtp As DateTimePicker) If valCheck Then newVal = dtp.Value If currVal.Year <> newVal.Year Then currSelected = Selection.Year ElseIf currVal.Month <> newVal.Month Then currSelected = Selection.Month ElseIf currVal.Day <> newVal.Day Then currSelected = Selection.Day End If dtp.Value = currVal valCheck = False End If End Sub Private Sub MyDateTimePicker_DropDown(sender As Object,e As EventArgs) Handles MyDateTimePicker.DropDown RemoveHandler MyDateTimePicker.MouseUp,AddressOf MyDateTimePicker_MouseUp End Sub Private Sub MyDateTimePicker_CloseUp(sender As Object,e As EventArgs) Handles MyDateTimePicker.CloseUp AddHandler MyDateTimePicker.MouseUp,AddressOf MyDateTimePicker_MouseUp CheckDTPSelection(MyDateTimePicker) End Sub Private Sub MyDateTimePicker_KeyUp(sender As Object,e As KeyEventArgs) Handles MyDateTimePicker.KeyUp If e.KeyValue = Keys.Left OrElse e.KeyValue = Keys.Right Then CheckDTPSelection(MyDateTimePicker) End If End Sub Private Sub MyDateTimePicker_MouseUp(sender As Object,e As MouseEventArgs) Handles MyDateTimePicker.MouseUp CheckDTPSelection(MyDateTimePicker) End Sub Private Sub MyDateTimePicker_ValueChanged(sender As Object,e As EventArgs) Handles MyDateTimePicker.ValueChanged Dim dtp As DateTimePicker = DirectCast(sender,DateTimePicker) RefreshSelection(dtp) End Sub Private Sub Btn_WhatsSelected_Click(sender As Object,e As EventArgs) Handles Btn_WhatsSelected.Click 'Show the current selected value in a MessageBox MessageBox.Show(currSelected.ToString()) End Sub