Friday, March 17, 2006

A winforms datetimepicker with Null binding support

The DateTimePicker in winforms 2.0 (and the previous versions) does not support null binding.

Using generics and a few lines of code, I created my own bindable control.

Here it is:


public class DateTimePickerNullable: System.Windows.Forms.DateTimePicker, INotifyPropertyChanged
{
public DateTimePickerNullable()
: base()
{
ShowCheckBox = true;
}

[Bindable(true)]
public Nullable BindableValue
{
get
{
if (Checked)
{
return Value;
}
else
{
return null;
}
}
set
{
if (value.HasValue && value.Value > DateTime.MinValue)
{
this.Checked = true;
}
else
{
this.Checked = false;
}
}
}

public new bool Checked
{
get { return base.Checked; }
set
{
base.Checked = value;
OnPropertyChanged("BindableValue");
}
}

protected override void OnCloseUp(EventArgs eventargs)
{
base.OnCloseUp(eventargs);
OnPropertyChanged("BindableValue");
}


#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

#endregion
}