作法:使用 DateTimePicker 控制項顯示時間How to: Display Time with the DateTimePicker Control

如果您希望應用程式可讓使用者選取日期和時間,並在指定的格式中顯示該日期和時間,請使用 DateTimePicker 控制項。If you want your application to enable users to select a date and time, and to display that date and time in the specified format, use the DateTimePicker control. 下列程序示範如何使用 DateTimePicker 控制項來顯示時間。The following procedure shows how to use the DateTimePicker control to display the time.

使用 DateTimePicker 控制項顯示時間To display the time with the DateTimePicker control

  1. Format 屬性設定為 TimeSet the Format property to Time

    timePicker.Format = DateTimePickerFormat.Time;
    
    timePicker.Format = DateTimePickerFormat.Time
    
  2. DateTimePickerShowUpDown 屬性設定為 trueSet the ShowUpDown property for the DateTimePicker to true.

    timePicker.ShowUpDown = true;
    
    timePicker.ShowUpDown = True
    

範例Example

下列程式碼範例示範如何建立 DateTimePicker,可讓使用者僅能選擇一個時間。The following code sample shows how to create a DateTimePicker that enables users to choose a time only.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TimePickerApplication
{
    public class Form1 : Form
    {
        public Form1()
        {
            InitializeTimePicker();
        }
        private DateTimePicker timePicker;

        private void InitializeTimePicker()
        {
            timePicker = new DateTimePicker();
            timePicker.Format = DateTimePickerFormat.Time;
            timePicker.ShowUpDown = true;
            timePicker.Location = new Point(10, 10);
            timePicker.Width = 100;
            Controls.Add(timePicker);
        }
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
        
    }
}
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    Public Sub New()
        InitializeTimePicker()

    End Sub
    Private timePicker As DateTimePicker


    Private Sub InitializeTimePicker()
        timePicker = New DateTimePicker()
        timePicker.Format = DateTimePickerFormat.Time
        timePicker.ShowUpDown = True
        timePicker.Location = New Point(10, 10)
        timePicker.Width = 100
        Controls.Add(timePicker)

    End Sub

    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())

    End Sub
End Class

編譯程式碼Compiling the Code

這個範例需要:This example requires:

  • System、System.Data、System.Drawing 和 System.Windows.Forms 組件的參考。References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies.

另請參閱See also