将DateTimePicker的值设置为null。

13

我正在开发一个带有两个 DateTimePicker 控件的 WinForms UI。最初,我希望将控件的值设置为 null,直到用户选择日期。如果用户没有选择日期,它将向数据库传递空值。

默认情况下,它采用当前日期。

请您建议或附加代码片段,以帮助我解决问题。

我已经尝试设置 MinDate 属性,但它并不起作用。

该代码使用 C# .Net 编写。

谢谢,Manali。


当你说“它不起作用”时,你确切的意思是什么? - Jon Skeet
2
可空的日期选择器是一个受欢迎的自定义控件项目。您可以在codeproject.com上找到许多这样的控件。 - Hans Passant
我的意思是我无法将DateTimePicker的MinDate值设置为null或空字符串。你能帮忙吗? - Manali
可能是DateTimePicker Null Value (.NET)的重复问题。 - bluish
8个回答

16
我认为最好的解决方案是使用内置复选框,告知用户是否指定了值。
设置控件属性ShowCheckBox = true 当将值绑定到它时,执行以下操作:
 if (value == DateTime.MinValue) {
    datePicker.Checked = false;
  } else {
    datePicker.Checked = true;
    datePicker.Value = value;
  }

读取值时,请检查Checked属性。

如果您不喜欢未选中时显示的值,可以将其与其他建议结合使用。

  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.
  }

那可能是最好的方式,也是最不破坏性的。 - goamn
这是最佳解决方案。 .Checked 属性默认为 TRUE,因此最初将其设置为 FALSE,并在 .ValueChanged 事件触发时它将自动将 .Checked 属性设置为 TRUE。 - Bimmerbound

9

我知道这篇文章已经有点老了,但其他人可能仍然会发现它有用。它相当优美而简洁。我使用它与 .Net 4.0 DateTimePicker 一起使用,但早期版本只需要进行少量调整即可。它利用了 MinDate 和 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; 

3
为了在 DateTimePicker 控件中显示 null 值,请在 Designer.cs 文件中进行以下更改:
this.DateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.DateTimePicker.CustomFormat = " ";

当用户选择日期时,在控件的ValueChanged属性中编写代码,并根据您的需求进行格式设置。这样将在控件中显示日期。
上述方法只会在UI中显示空白控件,但是默认值仍然是当前日期。
如果您希望将值设置/初始化为null或空字符串:
1. 声明一个临时字符串变量,例如temp。 2. temp = DateTimePicker.CustomFormat.ToString(); 3. 检查temp是否为空字符串。如果是,则按照您的喜好进行处理。
这是我找到的最简单的解决方法。

你不需要编辑 Designer.cs 文件:只需在属性窗口中将格式设置为自定义,将 CustomFormat 字段留空即可。 - Jack Griffin

2
假设dtpStartDate是您的DateTimePicker控件。
在Page_Load中编写以下代码-
`dtpStartDate.Format = DateTimePickerFormat.Custom;
            dtpStartDate.CustomFormat = " ";`

在Value_Changed事件中编写以下代码 -
`startDate = Convert.ToString(dtpStartDate.Value);
        dtpStartDate.Format = DateTimePickerFormat.Short;`

在这里选择“短”作为格式,你可以选择“长”和其他可用选项。


1

也许您需要创建一个外观类似于文本框的UserControl,当用户单击日历时显示,选择日期后将其设置为文本框。它将允许空值。

DateTimePicker不允许为空。


你的意思是说,我需要在日期时间选择器上方放置一个文本框吗? - Manali
请查看此链接:http://www.codeproject.com/KB/selection/NullableDateTimePicker.aspx - JTorrecilla

1

我希望这可以帮助您 链接1 在选择器字段中显示空白

还有这个 链接2


可以使用DateTimePicker的"CustomFormat"属性来显示null / empty string,但是在提取值时,它会给出当前日期。如果DateTimePicker字段未被选择,则应该实际上返回null或empty string。 - Manali
1
是的,正是因为日期选择器不支持DateTimeNullable属性,第二个链接将帮助您通过CodeProject示例实现相同的效果,该示例重写了Value属性以接受DateTime?。这是实现您想要的唯一方法。 - V4Vendetta

0

这是我使用的可空日期时间选择器的代码:

    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 = " ";

1
通常情况下,即使是非常简单的答案,如果您能解释一下您的答案,那么它们会更受欢迎。 - JoelC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接