如何在 C# 中设置 DateTimePicker 的大小?

原文:https://www . geeksforgeeks . org/如何设置 c-sharp 中日期时间选择器的大小/

在 Windows 窗体中,DateTimePicker 控件用于在窗体中选择和显示具有特定格式的日期/时间。在日期选择器控件中,可以使用大小属性设置日期选择器的大小。该属性以像素为单位表示高度和宽度。您可以通过两种不同的方式设置此属性:

1。设计时间:设置日期时间选择器的大小是最简单的方法,如以下步骤所示:

  • Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp

  • Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:

  • Step 3: After drag and drop you will go to the properties of the DateTimePicker and set the Size of the DateTimePicker as shown in the below image:

    输出:

2。运行时:比上面的方法稍微复杂一点。在此方法中,您可以借助给定的语法以编程方式设置 DateTimePicker 控件的大小:

public System.Drawing.Size Size { get; set; }

这里,“大小”以像素为单位表示高度和宽度。以下步骤显示了如何动态设置日期选择器的大小:

  • 步骤 1: 使用 DateTimePicker 类提供的 DateTimePicker()构造函数创建一个 DateTimePicker。

    ```cs // Creating a DateTimePicker DateTimePicker dt = new DateTimePicker();

    ```

  • 步骤 2: 创建日期选择器后,设置由日期选择器类提供的日期选择器的大小属性。

    ```cs // Setting the size dt.Size = new Size(292, 26);

    ```

  • 第 3 步:最后使用下面的语句将这个 DateTimePicker 控件添加到表单中:

    ```cs // Adding this control to the form this.Controls.Add(dt);

    ```

示例:

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

namespace WindowsFormsApp48 {

public partial class Form1 : Form {

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // Creating and setting the
        // properties of the Label
        Label lab = new Label();
        lab.Location = new Point(183, 162);
        lab.Size = new Size(172, 20);
        lab.Text = "Select Date and Time";
        lab.Font = new Font("Comic Sans MS", 12);

        // Adding this control to the form
        this.Controls.Add(lab);

        // Creating and setting the 
        // properties of the DateTimePicker
        DateTimePicker dt = new DateTimePicker();
        dt.Location = new Point(360, 162);
        dt.Size = new Size(292, 26);
        dt.MaxDate = new DateTime(2500, 12, 20);
        dt.MinDate = new DateTime(1753, 1, 1);
        dt.Format = DateTimePickerFormat.Long;
        dt.Name = "MyPicker";
        dt.Font = new Font("Comic Sans MS", 12);
        dt.Visible = true;
        dt.Value = DateTime.Today;

        // Adding this control 
        // to the form
        this.Controls.Add(dt);
    }
}
}

输出: