📌  相关文章
📜  如何在C#中设置DateTimePicker的位置?

📅  最后修改于: 2021-05-29 21:01:49             🧑  作者: Mango

在Windows窗体中,DateTimePicker控件用于选择和显示窗体中具有特定格式的日期/时间。在DateTimePicker控件中,可以使用Location属性在窗体上设置DateTimePicker的位置。此属性为您提供控件的坐标。您可以通过两种不同的方式设置此属性:

1.设计时:这是设置DateTimePicker位置的最简单方法,如以下步骤所示:

  • 第1步:创建一个Windows窗体,如下图所示:

    Visual Studio->文件->新建->项目-> WindowsFormApp

  • 步骤2:接下来,将DateTimePicker控件从工具箱拖放到窗体,如下图所示:

  • 步骤3:拖放之后,您将转到DateTimePicker的属性,并设置DateTimePicker的位置,如下图所示:

    输出:

2.运行时:比上述方法有些棘手。在此方法中,可以借助给定的语法以编程方式设置DateTimePicker控件的位置:

public System.Drawing.Point Location { get; set; }

在这里,Point包含DateTimePicker控件的坐标。以下步骤显示如何动态设置DateTimePicker的位置:

  • 步骤1:使用DateTimePicker类提供的DateTimePicker()构造函数创建DateTimePicker。
    // Creating a DateTimePicker
    DateTimePicker dt = new DateTimePicker();
    
  • 步骤2:创建DateTimePicker之后,设置DateTimePicker类提供的DateTimePicker的Location属性。
    // Setting the location
    dt.Location = new Point(360, 162);
    
  • 步骤3:最后,使用以下语句将此DateTimePicker控件添加到表单中:
    // 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);
    }
}
}

输出: