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
}

1 Comments:

Anonymous Anonymous said...

I am getting this error:
'System.Nullable': static types cannot be used as return types'
and
'System.Nullable': static types cannot be used as parameters'

This is when I get to here:
public Nullable BindableValue
{
get

and here
public Nullable BindableValue
{
set
Any help?

7:48 AM  

Post a Comment

Links to this post:

Create a Link

<< Home