将 DateTimePicker 值设置为 null

发布于 2024-11-06 07:13:24 字数 257 浏览 5 评论 0原文

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

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

您能否提出一些建议或附加一段代码来帮助我。

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

代码采用 C# .Net。

谢谢, 马纳里。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

软的没边 2024-11-13 07:13:25

我知道这是一篇较旧的文章,但其他人可能仍然觉得这很有用。它相当优雅和简洁。我将其与 .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; 

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; 
黑寡妇 2024-11-13 07:13:25

要在 DateTimePicker 控件中显示空值,请在 Designer.cs 文件中进行以下更改:

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

当用户选择日期时,在 ValueChanged 中编写代码code> 控件的属性并根据您的需要设置格式。这将在控件中显示日期。

上面的控件在 UI 中仅显示为空白,但默认值仍然是当前日期。

如果要将值设置/初始化为 null 或空字符串:

  1. 声明一个临时字符串变量 temp
  2. temp = DateTimePicker.CustomFormat.ToString();
  3. 检查 temp 是否为空字符串。如果是的话,按你喜欢的方式处理。

这是我发现的最简单的解决方法。

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.

叫嚣ゝ 2024-11-13 07:13:25

假设 dtpStartDate 是您的 DateTimePicker 控件。

在 Page_Load 中写入此代码 -

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

在 Value_Changed 事件中写入此代码 -

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

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

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.

绳情 2024-11-13 07:13:25

可能您需要创建一个具有文本框外观的用户控件,当用户单击日历显示时,当您选择日期时将其设置为文本框。它将允许空值。

DateTimePicker 不允许为 null。

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.

海未深 2024-11-13 07:13:25

我希望这对您有帮助 Link1 < em>要在选择器字段中显示空白

,这也是Link2

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

and this too Link2

默嘫て 2024-11-13 07:13:25

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

    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

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
羁〃客ぐ 2024-11-13 07:13:25
dateTimePicker1.CustomFormat = " ";
dateTimePicker1.CustomFormat = " ";
じ违心 2024-11-13 07:13:24

我认为最好的解决方案是使用内置复选框来告诉用户是否指定了值。

设置控件属性 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.
  }

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.
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文