从DateTimePicker获取选定的值

问题描述 投票:7回答:2

我想从VB中的DateTimePicker中选择一个值(如果我只选择日值,那么我只想获得选定的日值。)

enter image description here

在这张图片中,我从这个DateTimePicker中选择了(蓝色标记的)年份值。所以我只需要今年的价值。

TextBox的情况下,我可以使用选择值

TextEndTime.SelectedText

是否有任何语法或方法可以从DateTimePicker中获取选定的值?

vb.net winforms datetimepicker
2个回答
3
投票

由于可以使用箭头键操纵DateTimePicker-control,您可以使用SendKeys更改当前选定的值。

以下示例获取DateTime的当前DateTimePicker值,并在发送↑键后将值与新值进行比较。最后它将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

-5
投票

您需要从Value创建DateTime对象。

DateTime selectedDate = new DataTime(TextEndTime.Value);
int year = selectedDate.Year;

VB版。

Dim selectedDate As DateTime = New DataTime(TextEndTime.Value)
Dim year As Integer = selectedDate.Year
© www.soinside.com 2019 - 2024. All rights reserved.