LOGIN    REGISTER    YOUR CART

homepage
VisualHint's blog
2007
Jun27

More about null values in a DateTimePicker

Before releasing version 1.0 of Smart FieldPackEditor.Net I must ensure that the support for null values is really complete. So what does this feature really involves?

First let’s remind in what contexts a DateTimePicker can operate:

  1. It can be a standalone control and completely encapsulate a DateTime value.
  2. You can manually bind one of your properties to the component’s Value property.
  3. You can embed the component in a container like the DataGridView. In this case, the component will be automatically bound to a particular column of a database table via a DataSource.
  4. You can embed the component in a container like the PropertyGrid. This will bind the component to a DateTime property somewhere in your code.

In the first case, the support for null values is straightforward. The component stores the DateTime value as an object so it can use anything for the object representing a null value.

We have to think a bit more for the other cases. What can be the type of your property in a target instance? Obviously this can be an object (not very common to store a date but still feasible), a nullable DateTime (aka “DateTime?”) or a DateTime. In the first case, there is again no difficulty: we can assign anything we want to represent a null value. In the second case we have less choices: it can be null or a particular DateTime value that is out of the bounds specified by the MinDate and MaxDate properties of the DateTimePicker (anything before 1753 will be fine). In the last case, with a DateTime type, there are no choices: you can only use a specific DateTime value like 01/01/0001 for example.

Now let’s relate the context of use with the data type you have in your client application:

In case 2, you can target any of the three data types we just saw. The value representing null will be chosen in accordance with the restrisctions seen above and setup in the editor. In case 3, the value representing null will usually be DBNull.Value. But for historical reasons you may have a specific DateTime value in your database that represents the null value. In both cases, again, the editor must be setup for that. In case 4, well, it’s like case 2.

Everything that has been mentioned so far implies that we need a set of properties to properly setup the DateTimePicker:

  • NullValue: instructs the editor about what will represent a null value. It will typically be null, DBNull.Value or a specific DateTime value. But it could also be a string like “nothing”.
  • NullText: the string displayed in the editor when Value == NullValue.
  • HasValue: convenient property to test for nullity.

If you use the DateTimePicker in other very specific contexts and you need support for null value, please let me know.