13

I am developing a WinForms UI with two DateTimePicker controls. Initially I want to set the value of the controls to null until a user selects a date. If the user does not select a date, it will pass a value of null to the database.

By default it takes the current date.

Could you plz suggest something or attach a piece of code which will help me out.

I have tried setting the MinDate property but it doesn't work.

The code is in C# .Net.

Thanks, Manali.

SharpC
  • 6,974
  • 4
  • 45
  • 40
Manali
  • 295
  • 3
  • 5
  • 16

8 Answers8

16

I think the best solution is to use the build-in checkbox that tell the user if a value is specified or not.

Set the control property ShowCheckBox = true

When you bind the value to it do something like

 if (value == DateTime.MinValue) {
    datePicker.Checked = false;
  } else {
    datePicker.Checked = true;
    datePicker.Value = value;
  }

When reading back the value check the Checked property.

If you don't like the displayed value when it's unchecked, you can combine that with the other suggestions.

  if (!datePicker.Checked) {
    // hide date value since it's not set
    datePicker.CustomFormat = " ";
    datePicker.Format = DateTimePickerFormat.Custom;
  } else {
    datePicker.CustomFormat = null;
    datePicker.Format = DateTimePickerFormat.Long; // set the date format you want.
  }
Zyo
  • 1,934
  • 21
  • 25
  • That is probably the best way, and least hacky. – goamn Aug 12 '14 at 23:46
  • This is the best solution. The .Checked property defaults to TRUE so just set to FALSE initially and when the .ValueChanged event fires it will automatically set the .Checked property to TRUE. – Bimmerbound Oct 05 '16 at 14:18
9

I know this is an older post, but others might still find this useful. It is fairly elegant and concise. I used this with a .Net 4.0 DateTimePicker but earlier versions should work with minimal tweaking. It leverages MinDate and Checked.

    // Use ValueChanged to decide if the value should be displayed:
    dateTimePicker1.ValueChanged += (s, e) => { dateTimePicker1.CustomFormat = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ? "MM/dd/yyyy" : " "; };

    //When getting the value back out, use something like the following:
    DateTime? dt = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ?  (DateTime?) dateTimePicker1.Value : null; 
    // or
    DateTime dt2 = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ?  dateTimePicker1.Value : DateTime.MinValue; 
K Kimble
  • 249
  • 3
  • 8
3

To display the null value in DateTimePicker control, Make the following changes in the Designer.cs file:

this.DateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.DateTimePicker.CustomFormat = " ";

When user selects a date, code-in the ValueChanged property of the control and make the format according to your needs. This will display the date in the control.

The above one only display's the control as blank in UI, however the default value will still be the current date.

If you want to set/initialize the value as null or empty string:

  1. declare a temporary string variable say temp
  2. temp = DateTimePicker.CustomFormat.ToString();
  3. check whether temp is an empty string. If so handle as you like.

This is the easiest workaround I found.

hichris123
  • 10,145
  • 15
  • 56
  • 70
Manali
  • 295
  • 3
  • 5
  • 16
  • You don't need to edit the Designer.cs : just set the Format to Custom in the Properties window leaving the CustomFormat field blank. – Jack Griffin Mar 19 '17 at 07:29
2

Let suppose dtpStartDate is your DateTimePicker control.

Write this code in Page_Load-

`dtpStartDate.Format = DateTimePickerFormat.Custom;
            dtpStartDate.CustomFormat = " ";`

Write this code in Value_Changed event-

`startDate = Convert.ToString(dtpStartDate.Value);
        dtpStartDate.Format = DateTimePickerFormat.Short;`

here selected 'short' as Format. You can select 'Long' and other option available.

1

May be you need to create a UserControl withe the Appereance of a TextBox,and when the user click on a Calender Show, when you select a Date set it to the TextBox. It will allow nulls values.

The DateTimePicker does not allow null.

JTorrecilla
  • 208
  • 1
  • 4
1

I hope this should help you Link1 To display blank in the picker field

and this too Link2

Community
  • 1
  • 1
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
  • Displaying null/empty string can be done with the property called "CustomFormat" of DateTimePicker, but when extracting the value, it gives the current date. Which should actually return null or empty string if the DateTimePicker field is not chosen. – Manali May 11 '11 at 02:58
  • 1
    Yes exactly thats because datepicker doesn't support a `Nullable` property for `DateTime`, the second link would help you in achieving the same via the codeproject sample which overrides the `Value` property to accept `DateTime?`. This is the only way to achieve what you want. – V4Vendetta May 11 '11 at 04:30
0

This is the code of a nullable datetime picker that I use:

    Public Class DateTimePickerNullable
    Inherits DateTimePicker

    Public Shadows Event GotFocus(sender As Object, e As EventArgs)
    Public Shadows Event LostFocus(sender As Object, e As EventArgs)

    Private fvalue As DateTime?
    Private NoValueChange As Boolean = False
    Public Shadows Property Value As DateTime?
        Get
            Return fvalue
        End Get
        Set(value As DateTime?)
            fvalue = value
            If fvalue Is Nothing Then
                Me.Format = DateTimePickerFormat.Custom
                Me.CustomFormat = Space(Now.ToShortDateString.Length)
                NoValueChange = True
                MyBase.Value = Now
                NoValueChange = False
            Else
                Me.Format = DateTimePickerFormat.Short
                NoValueChange = True
                MyBase.Value = value.Value
                NoValueChange = False
            End If
        End Set
    End Property

    Protected Overrides Sub OnValueChanged(eventargs As EventArgs)
        If Not NoValueChange Then
            Value = MyBase.Value
        End If
        MyBase.OnValueChanged(eventargs)
    End Sub

    Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
        If e.KeyCode = Keys.Delete Then
            Value = Nothing
        End If
        If Me.Format = DateTimePickerFormat.Custom Then
            Try
                If Char.IsNumber(ChrW(e.KeyCode)) Then
                    If Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.ToLower.StartsWith("m") Then
                        Value = New Date(Now.Year, CInt(ChrW(e.KeyCode).ToString), Now.Day)
                    Else
                        Value = New Date(Now.Year, Now.Month, CInt(ChrW(e.KeyCode).ToString))
                    End If
                    SendKeys.Send(ChrW(e.KeyCode))
                    Exit Sub
                End If
            Catch
            End Try
        End If
        MyBase.OnKeyDown(e)
    End Sub

    Private HasFocus As Boolean = False
    Protected Overrides Sub OnGotFocus(e As EventArgs)
        MyBase.OnGotFocus(e)
        If Not HasFocus Then
            HasFocus = True
            RaiseEvent GotFocus(Me, New EventArgs)
        End If
    End Sub

    Protected Overrides Sub OnValidated(e As EventArgs)
        MyBase.OnValidated(e)
        HasFocus = False
        RaiseEvent LostFocus(Me, New EventArgs)
    End Sub
End Class
-1
dateTimePicker1.CustomFormat = " ";
Undo
  • 25,519
  • 37
  • 106
  • 129
  • 1
    Typically answers are better received if you give an explanation of your answer, even for very simple answers. – JoelC Apr 30 '15 at 19:45