24

nullユーザーが値を入力できるように、.NET DateTimePicker コントロールを変更する最も簡単で堅牢な方法は何ですか?

4

6 に答える 6

47

You don't need to modify it to do this.

The DateTimePicker in .net actually has a checkbox built-in.

Set the ShowCheckBox property to true.

Then you can use the Checked property to see if the user has entered a value.

http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.showcheckbox(VS.80).aspx

于 2009-11-19T12:32:48.187 に答える
6

Nullable DateTimePickerの作成に関するこの CodeProject の記事からのアプローチを次に示します。

および標準コントロールの検証を維持しながら、値を としてValue受け入れるようにプロパティをオーバーライドしました。NullDateTime.MinValueMinValueMaxValue

これは、記事のカスタム クラス コンポーネントのバージョンです。

public class NullableDateTimePicker : System.Windows.Forms.DateTimePicker
{
    private DateTimePickerFormat originalFormat = DateTimePickerFormat.Short;
    private string originalCustomFormat;
    private bool isNull;

    public new DateTime Value
    {
        get => isNull ? DateTime.MinValue : base.Value;
        set
        {
            // incoming value is set to min date
            if (value == DateTime.MinValue)
            {
                // if set to min and not previously null, preserve original formatting
                if (!isNull)
                {
                    originalFormat = this.Format;
                    originalCustomFormat = this.CustomFormat;
                    isNull = true;
                }

                this.Format = DateTimePickerFormat.Custom;
                this.CustomFormat = " ";
            }
            else // incoming value is real date
            {
                // if set to real date and previously null, restore original formatting
                if (isNull)
                {
                    this.Format = originalFormat;
                    this.CustomFormat = originalCustomFormat;
                    isNull = false;
                }

                base.Value = value;
            }
        }
    }

    protected override void OnCloseUp(EventArgs eventargs)
    {
        // on keyboard close, restore format
        if (Control.MouseButtons == MouseButtons.None)
        {
            if (isNull)
            {
                this.Format = originalFormat;
                this.CustomFormat = originalCustomFormat;
                isNull = false;
            }
        }
        base.OnCloseUp(eventargs);
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);

        // on delete key press, set to min value (null)
        if (e.KeyCode == Keys.Delete)
        {
            this.Value = DateTime.MinValue;
        }
    }
}
于 2008-11-12T15:56:47.480 に答える
4

DateTimePickerを有効/無効にする「通知を有効にする」などのラベルの付いた追加のチェックボックスを配置します。

于 2008-11-12T15:50:18.103 に答える
2

Tri の解決策は私にとってはうまくいかなかったので、 Grazioli氏と彼はそれについて何かをしたと思いました。

于 2008-12-09T13:54:21.877 に答える
0

このコントロールの固有の問題に関するコードコメントにいくつかの調査結果があるソリューションの長い道のりを投稿しました。

日時ピッカーの null 値

于 2011-12-23T11:33:59.053 に答える