在C#中将DateTimePicker设置为空

3

我有一个 DateTimePicker,当我将其保存到数据库时,希望将其设置为 null,但默认情况下它具有今天的值。如果我想删除它并清空 DateTimePicker,我无法实现。

我尝试将其放入加载表单中:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";

实际上它是有效的,但如果我想设置一个日期,它将无法显示在 DateTimePicker 中。你有任何想法如何解决它吗?


你看不到任何东西是因为你破坏了格式,而不是将其设置为空。 - Patrick Hofman
我知道。但是如果我想将其设置为null并且想要添加日期,我可以吗?@PatrickHofman - Rekcs
一个UI控件与数据库有什么关系?如果你不想保存控件中输入的值,那就不要将其传递给数据库。DateTime的默认值是DateTime.MinValue。 - Panagiotis Kanavos
1个回答

1

我曾经编写过一个日期时间选择器,可以接受空值(并且额外提供了周数的功能)。

[DefaultEvent("ValueChanged")]
[ComVisible(true)]
[DefaultProperty("Value")]
[DefaultBindingProperty("Value")]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[Designer("System.Windows.Forms.Design.DateTimePickerDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class NullableDateTimePicker : DateTimePicker
{
    #region Externals
    private const int GWL_STYLE = (-16);
    private const int MCM_FIRST = 0x1000;
    private const int MCM_GETMINREQRECT = (MCM_FIRST + 9);
    private const int MCS_WEEKNUMBERS = 0x4;
    private const int DTM_FIRST = 0x1000;
    private const int DTM_GETMONTHCAL = (DTM_FIRST + 8);

    [DllImport("User32.dll")]
    public static extern int GetWindowLong(IntPtr h, int index);

    [DllImport("User32.dll")]
    public static extern int SetWindowLong(IntPtr h, int index, int value);

    [DllImport("User32.dll")]
    private static extern IntPtr SendMessage(IntPtr h, int msg, int param, int data);

    [DllImport("User32.dll")]
    private static extern int SendMessage(IntPtr h, int msg, int param, ref Rectangle data);

    [DllImport("User32.dll")]
    private static extern int MoveWindow(IntPtr h, int x, int y, int width, int height, bool repaint);

    [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
    private static extern IntPtr GetParent(IntPtr hWnd);
    #endregion

    #region General
    public NullableDateTimePicker()
    {
        this.ShowCheckBox = true;
    }
    #endregion

    #region Properties
    /// <summary>
    /// Gets or sets the date/time value assigned to the control.
    /// </summary>
    /// <exception cref="System.ArgumentOutOfRangeException">
    /// The set value is less than System.Windows.Forms.DateTimePicker.MinDate or more than System.Windows.Forms.DateTimePicker.MaxDate.
    /// </exception>
    [RefreshProperties(RefreshProperties.All)]
    [Bindable(true)]
    public new DateTime? Value
    {
        get
        {
            if (!base.Checked)
            {
                return null;
            }

            return base.Value;
        }
        set
        {
            if (value.HasValue)
            {
                base.Checked = true;

                if (this.Format == DateTimePickerFormat.Short)
                {
                    base.Value = value.Value.Date;
                }
                else if (this.Format == DateTimePickerFormat.Time)
                {
                    base.Value = default(DateTime).Add(value.Value.TimeOfDay);
                }
                else
                {
                    base.Value = value.Value;
                }
            }
            else
            {
                base.Checked = false;
            }
        }
    }

    /// <summary>
    /// Gets or sets whether to show week numbers.
    /// </summary>
    [Browsable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    [DefaultValue(false)]
    public bool ShowWeekNumbers
    {
        get;
        set;
    }
    #endregion

    #region Week numbers
    /// <summary>
    /// Raises the System.Windows.Forms.DateTimePicker.DropDown event.
    /// </summary>
    /// <param name="e">An System.EventArgs that contains the event data.</param>
    protected override void OnDropDown(EventArgs e)
    {
        IntPtr monthView = SendMessage(this.Handle, DTM_GETMONTHCAL, 0, 0);
        int style = GetWindowLong(monthView, GWL_STYLE);

        if (this.ShowWeekNumbers)
        {
            style = style | MCS_WEEKNUMBERS;
        }
        else
        {
            style = style & ~MCS_WEEKNUMBERS;
        }

        Rectangle rect = new Rectangle();
        SetWindowLong(monthView, GWL_STYLE, style);
        SendMessage(monthView, MCM_GETMINREQRECT, 0, ref rect);
        MoveWindow(monthView, 0, 0, rect.Right + 3, rect.Bottom, true);

        //
        // Resize the surrounding window to let the new text fit
        //
        IntPtr parent = GetParent(monthView);

        Rectangle mainRect = new Rectangle();
        SendMessage(parent, MCM_GETMINREQRECT, 0, ref mainRect);
        MoveWindow(parent, 0, 0, mainRect.Right + 6, mainRect.Bottom + 6, true);

        base.OnDropDown(e);
    }
    #endregion
}

它显示一个复选框以允许空值,而new Value属性也允许null,因此它可以在设计师和代码中都起作用。

它显示了一些错误,因为StringifyFormatNativeMethods不存在。 - Rekcs
如果我勾选了“CheckBox”,它会将DateTimePicker设置为Null吗? - Rekcs
不是,反过来。 - Patrick Hofman
如果我取消勾选它呢? - Rekcs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接