Results 1 to 11 of 11

Thread: [2.0] Binding to my NullableDateTimePicker control

Threaded View

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276

    Question [2.0] Binding to my NullableDateTimePicker control

    With the addition of Nullable Types to C# 2.0, I wrote my own NullableDateTimePicker control in very few lines of code, as opposed to the nullable DateTimePicker controls I've found that were written for C# 1.1.


    csharp Code:
    1. public partial class NullableDateTimePicker : DateTimePicker
    2. {
    3.     private DateTime? dtNullable;
    4.  
    5.     public NullableDateTimePicker()
    6.     {
    7.         base.Format = DateTimePickerFormat.Custom;
    8.         base.CustomFormat = " ";
    9.     }
    10.  
    11.     public new DateTime? Value
    12.     {
    13.  
    14.         get
    15.         {
    16.             if (dtNullable.HasValue)
    17.                 return base.Value;
    18.  
    19.             return null;
    20.         }
    21.  
    22.         set
    23.         {
    24.             if (value == null)
    25.                 dtNullable = null;
    26.             else
    27.                 dtNullable = base.Value = value.Value;
    28.  
    29.             OnValueChanged(EventArgs.Empty);
    30.         }
    31.     }
    32.  
    33.     protected override void OnValueChanged(EventArgs eventargs)
    34.     {
    35.  
    36.         if (this.dtNullable.HasValue)
    37.         {
    38.             base.Format = DateTimePickerFormat.Short;
    39.         }
    40.         else
    41.         {
    42.             base.Format = DateTimePickerFormat.Custom;
    43.             base.CustomFormat = " ";
    44.         }
    45.  
    46.         base.OnValueChanged(eventargs);
    47.     }
    48.  
    49.     protected override void OnCloseUp(EventArgs eventargs)
    50.     {
    51.         if (Control.MouseButtons == MouseButtons.None)
    52.         {
    53.             this.Value = base.Value;
    54.         }
    55.  
    56.         base.OnCloseUp(eventargs);
    57.     }
    58. }

    Which is alright except if I bind the Value property and the binding source returns a DBNull.Value then I get the following error:

    error Code:
    1. Invalid cast from 'System.DateTime' to 'System.Nullable`

    How can I represent a DateTime so that it may contain a valid DateTime, and instead of null, DBNull.Value?
    Last edited by wey97; Oct 24th, 2007 at 08:26 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width