Skip to content

Instantly share code, notes, and snippets.

@masaru-b-cl
Created June 15, 2012 05:09
Show Gist options
  • Save masaru-b-cl/2934762 to your computer and use it in GitHub Desktop.
Save masaru-b-cl/2934762 to your computer and use it in GitHub Desktop.
Null可能なDateTimePicker
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Threading;
namespace ClassLibrary1
{
public partial class NullableDateTimePicker : DateTimePicker
{
private DateTimePickerFormat format;
public new string CustomFormat { get; set; }
[Browsable(true)]
[DefaultValue(DateTimePickerFormat.Long), TypeConverter(typeof(Enum))]
public new DateTimePickerFormat Format
{
get
{
return this.format;
}
set
{
this.format = value;
SetFormat();
OnFormatChanged(EventArgs.Empty);
}
}
private string formatAsString;
private string FormatAsString
{
get
{
return formatAsString;
}
set
{
formatAsString = value;
base.CustomFormat = value;
}
}
private Boolean isNull;
public new DateTime? Value
{
get
{
if (isNull) return null;
return base.Value;
}
set
{
if (value == null || !value.HasValue)
{
SetToNullValue();
}
else
{
SetToDateTimeValue();
base.Value = value.Value;
}
}
}
private void SetToNullValue()
{
this.isNull = true;
base.CustomFormat = String.IsNullOrEmpty(this.NullValue) ? " " : "'" + this.NullValue + "'";
}
private void SetToDateTimeValue()
{
if (this.isNull)
{
SetFormat();
this.isNull = false;
base.OnValueChanged(new EventArgs());
}
}
[Browsable(true)]
[Category("Behavior")]
[Description("�l��null�̂Ƃ��ɕ\������l��ݒ肵�܂��B")]
[DefaultValue(" ")]
public string NullValue { get; set; }
private void SetFormat()
{
var ci = Thread.CurrentThread.CurrentCulture;
var dateTimeFormat = ci.DateTimeFormat;
switch (this.format)
{
case DateTimePickerFormat.Long:
this.FormatAsString = dateTimeFormat.LongDatePattern;
break;
case DateTimePickerFormat.Short:
this.FormatAsString = dateTimeFormat.ShortDatePattern;
break;
case DateTimePickerFormat.Time:
this.FormatAsString = dateTimeFormat.ShortTimePattern;
break;
case DateTimePickerFormat.Custom:
this.FormatAsString = this.CustomFormat;
break;
}
}
protected override void OnCloseUp(EventArgs eventargs)
{
if (Control.MouseButtons == System.Windows.Forms.MouseButtons.None && this.isNull)
{
SetToDateTimeValue();
this.isNull = false;
}
base.OnCloseUp(eventargs);
}
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
this.Value = null;
OnValueChanged(EventArgs.Empty);
}
base.OnKeyUp(e);
}
public NullableDateTimePicker() : base()
{
InitializeComponent();
base.Format = DateTimePickerFormat.Custom;
this.Format = DateTimePickerFormat.Custom;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment