如果未选择日期,如何将 datetimepicker 设置为空值(c# winforms)

发布于 2024-09-04 09:04:21 字数 2619 浏览 9 评论 0原文

Binding b = new Binding( "Value", person, "BdayNullable", true );
dtBirthdayNullable.DataBindings.Add( b );
b.Format += new ConvertEventHandler( dtBirthdayNullable_Format );

b.Parse += new ConvertEventHandler( dtBirthdayNullable_Parse );

void dtBirthdayNullable_Format( object sender, ConvertEventArgs e )
{
    // e.Value is the object value, we format it to be what we want to show up in the control

    Binding b = sender as Binding;
    if ( b != null )
    {
        DateTimePicker dtp = (b.Control as DateTimePicker);
        if ( dtp != null )
        {
            if ( e.Value == DBvalue.value )
            {
                dtp.ShowCheckBox = true;
                dtp.Checked = false;

                // have to set e.Value to SOMETHING, since it's coming in as NULL
                // if i set to DateTime.Today, and that's DIFFERENT than the control's current 
                // value, then it triggers a CHANGE to the value, which CHECKS the box (not ok)
                // the trick - set e.Value to whatever value the control currently has.  
                // This does NOT cause a CHANGE, and the checkbox stays OFF.
                e.Value = dtp.Value;    
            }
            else
            {
                dtp.ShowCheckBox = true;
                dtp.Checked = true;
                // leave e.Value unchanged - it's not null, so the DTP is fine with it.
            }
        }
    }
}
void dtBirthdayNullable_Parse( object sender, ConvertEventArgs e )
{
    // e.value is the formatted value coming from the control.  
    // we change it to be the value we want to stuff in the object.

    Binding b = sender as Binding;
    if ( b != null )
    {
        DateTimePicker dtp = (b.Control as DateTimePicker);
        if ( dtp != null )
        {
            if ( dtp.Checked == false )
            {
                dtp.ShowCheckBox = true;
                dtp.Checked = false;
                e.Value = DBvalue.Value
            }
            else
            {
                DateTime val = Convert.ToDateTime( e.Value );
                e.Value =val;
            }
        }
    }
}

编辑

我在这里找到了一个很好的解决方案

http ://blogs.interknowlogy.com/danhanan/archive/2007/01/21/10847.aspx

这里是另一个完美的解决方案

http://www.mofeel.net/70-microsoft-public-dotnet-framework-windowsforms/8806.aspx

Binding b = new Binding( "Value", person, "BdayNullable", true );
dtBirthdayNullable.DataBindings.Add( b );
b.Format += new ConvertEventHandler( dtBirthdayNullable_Format );

b.Parse += new ConvertEventHandler( dtBirthdayNullable_Parse );

void dtBirthdayNullable_Format( object sender, ConvertEventArgs e )
{
    // e.Value is the object value, we format it to be what we want to show up in the control

    Binding b = sender as Binding;
    if ( b != null )
    {
        DateTimePicker dtp = (b.Control as DateTimePicker);
        if ( dtp != null )
        {
            if ( e.Value == DBvalue.value )
            {
                dtp.ShowCheckBox = true;
                dtp.Checked = false;

                // have to set e.Value to SOMETHING, since it's coming in as NULL
                // if i set to DateTime.Today, and that's DIFFERENT than the control's current 
                // value, then it triggers a CHANGE to the value, which CHECKS the box (not ok)
                // the trick - set e.Value to whatever value the control currently has.  
                // This does NOT cause a CHANGE, and the checkbox stays OFF.
                e.Value = dtp.Value;    
            }
            else
            {
                dtp.ShowCheckBox = true;
                dtp.Checked = true;
                // leave e.Value unchanged - it's not null, so the DTP is fine with it.
            }
        }
    }
}
void dtBirthdayNullable_Parse( object sender, ConvertEventArgs e )
{
    // e.value is the formatted value coming from the control.  
    // we change it to be the value we want to stuff in the object.

    Binding b = sender as Binding;
    if ( b != null )
    {
        DateTimePicker dtp = (b.Control as DateTimePicker);
        if ( dtp != null )
        {
            if ( dtp.Checked == false )
            {
                dtp.ShowCheckBox = true;
                dtp.Checked = false;
                e.Value = DBvalue.Value
            }
            else
            {
                DateTime val = Convert.ToDateTime( e.Value );
                e.Value =val;
            }
        }
    }
}

EDIT

i found a good solution here

http://blogs.interknowlogy.com/danhanan/archive/2007/01/21/10847.aspx

another perfect solution here

http://www.mofeel.net/70-microsoft-public-dotnet-framework-windowsforms/8806.aspx

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

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

发布评论

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

评论(6

夏末 2024-09-11 09:04:21

DateTimePicker 不能设置为 null,因为 DateTime 不能为 null,但您可以将它们设置为 DateTime.MinValue,这是未初始化的 DateTime 的默认值。然后您只需检查 dtp.Value = DateTime.MinValue 是否为空,如果是,则将其视为 null。

但是,如果您想真正区分何时未选择任何值,最简单的方法是将 DateTimePicker.ShowCheckBox 设置为 true,然后检查 dtp.Checked 并 if这是真的,你读取该值,否则你将其视为空值。

DateTimePickers can't be set to null because DateTime can't be null, but you can set them to DateTime.MinValue which is the default value for an uninitialized DateTime. And then you just check if the dtp.Value = DateTime.MinValue and if so, treat it as null.

However, if you want to really distinguish when no value has been selected, the easiest way is to set DateTimePicker.ShowCheckBox to true, and then you check dtp.Checked and if it's true, you read the value, otherwise you treat it as a null.

纸短情长 2024-09-11 09:04:21

您可以检查绑定源是否提供“空日期”或您不想显示的日期值。

如果是这样,请选择自定义格式:

yourDTP.Format = DateTimePickerFormat.Custom
yourDTP.CustomFormat = " "

添加“CloseUp”或“ValueChanged”事件处理程序以重置用户操作的格式:

yourDTP.Format = DateTimePickerFormat.Short

You can check if your binding source delivers a "null date" or a date value that you don't want to display.

If so, select custom format:

yourDTP.Format = DateTimePickerFormat.Custom
yourDTP.CustomFormat = " "

Add a "CloseUp" or "ValueChanged" event handler to reset the format on user action:

yourDTP.Format = DateTimePickerFormat.Short
子栖 2024-09-11 09:04:21

我喜欢 ShowCheckBox 选项。我会更进一步,用两个扩展方法封装它,以避免重复并具有更清晰的代码:

public static DateTime? NullableValue(this DateTimePicker dtp)
{
    return dtp.Checked ? dtp.Value : (DateTime?)null;
}

public static void NullableValue(this DateTimePicker dtp, DateTime? value)
{
    dtp.Checked = value.HasValue;
    if (value.HasValue) dtp.Value = value.Value;
}

然后,获取和设置代码如下所示:

dtpSafetyApprover.NullableValue(model.SafetyApproverDate); // set
model.SafetyApproverDate = dtpSafetyApprover.NullableValue(); // get

I like the ShowCheckBox option. I would take it one step further and encapsulate it with two extension methods to avoid duplication and have cleaner looking code:

public static DateTime? NullableValue(this DateTimePicker dtp)
{
    return dtp.Checked ? dtp.Value : (DateTime?)null;
}

public static void NullableValue(this DateTimePicker dtp, DateTime? value)
{
    dtp.Checked = value.HasValue;
    if (value.HasValue) dtp.Value = value.Value;
}

Then, the get and set code looks like:

dtpSafetyApprover.NullableValue(model.SafetyApproverDate); // set
model.SafetyApproverDate = dtpSafetyApprover.NullableValue(); // get
雨后彩虹 2024-09-11 09:04:21

最简单的方法是添加一个文本框并将visible属性设置为false。在日期选择器的 valuechanged 事件上,使用选择器控件的相同日期时间值填充文本框。检查文本框的值,如果空字符串将值设置为空。

The easiest way is to add a text box and set the visible property to false. On the valuechanged event of the date picker populate the text box with the same date time value of the picker control. Check the value of the text box if null string set the value to null.

最舍不得你 2024-09-11 09:04:21

这就是我解决它的方法。我不能有 NULLS,所以我将 1/1/1980 12am 定义为 MYNULLDATE。我对日期时间选择器的文本和值使用了数据绑定。我没有使用日期时间选择器中的复选框。我没有将格式从短格式更改为自定义格式。它似乎触发了 valuechanged 事件,所以我只是使用自定义并更改了自定义格式。我使用了一个流程面板和一个 NONBOUND 复选框位于日期时间选择器前面。

的代码示例

   private void dateTimePicker_ValueChanged(object sender, EventArgs e)
    {
        if (sender != null && sender.GetType() == typeof(DateTimePicker))
        {
            if (((DateTimePicker)(sender)).Value == MYNULLDATE)
            {
                ((DateTimePicker)(sender)).CustomFormat = " ";
                checkBoxDate.Checked = false;
            }
            else
            {
                ((DateTimePicker)(sender)).CustomFormat = "M/d/yyyy";
                checkBoxDate.Checked = true;
            }
        }

    }

非绑定复选框中

  private void checkBoxDate_Click(object sender, EventArgs e)
    {
        if (bindingSource != null && bindingSource.Current != null &&
             bindingSource.Current.GetType() == typeof(MyRecord))
        {
            MyRecord a = (MyRecord)bindingSource.Current;
            if (checkBoxDate.Checked == false)
            {
                a.Date = MYNULLDATE;
                dateTimePicker.Enabled = false;
            }
            else
            {
                if (a.Date == null || a.Date == MYNULLDATE)
                {
                    dateTimePicker.Enabled = true;
                    a.Date = DateTime.Now;
                }
            }
            bindingSource.ResetBindings(false);
        }
    }

this is how i solved it. I couldn't have NULLS so I defined 1/1/1980 12am as MYNULLDATE. I used databinding on the text and value of the datetimepicker. I did not use the checkbox in the datetimepicker. I did not alternat formats from short to custom. It appeared to fire valuechanged events so i just used custom and changed the customformat. I used a flowpanel and a NONBOUND checkbox to sit in front of the datetimepicker.

Sample of the code

   private void dateTimePicker_ValueChanged(object sender, EventArgs e)
    {
        if (sender != null && sender.GetType() == typeof(DateTimePicker))
        {
            if (((DateTimePicker)(sender)).Value == MYNULLDATE)
            {
                ((DateTimePicker)(sender)).CustomFormat = " ";
                checkBoxDate.Checked = false;
            }
            else
            {
                ((DateTimePicker)(sender)).CustomFormat = "M/d/yyyy";
                checkBoxDate.Checked = true;
            }
        }

    }

In the Non Bound CheckBox

  private void checkBoxDate_Click(object sender, EventArgs e)
    {
        if (bindingSource != null && bindingSource.Current != null &&
             bindingSource.Current.GetType() == typeof(MyRecord))
        {
            MyRecord a = (MyRecord)bindingSource.Current;
            if (checkBoxDate.Checked == false)
            {
                a.Date = MYNULLDATE;
                dateTimePicker.Enabled = false;
            }
            else
            {
                if (a.Date == null || a.Date == MYNULLDATE)
                {
                    dateTimePicker.Enabled = true;
                    a.Date = DateTime.Now;
                }
            }
            bindingSource.ResetBindings(false);
        }
    }
隔岸观火 2024-09-11 09:04:21

使用 Vs 2015 并没有成功绑定 DateTimePicker 控件。最简单的事情似乎就是简单地不绑定它 - 手动将对象的值传递给控件以及从控件传递给对象。几行代码就能让你省去很多麻烦......

private void BindData()
{
    // can't bind the datetimepicker, so handle it manually...
    if (o.myDate == null)
    {
        dtDatePicker.Checked = false;
    }
    else
    {
        dtDatePicker.Checked = true;
        dtDatePicker.Value = o.myDate.Value;
    }
}

private void Save()
{
    if (dtDatePicker.Checked)
    {
        o.myDate = dtDatePicker.Value;
    }
    else
    {
        o.myDate = null;
    }
}

Using Vs 2015 and having no luck binding a DateTimePicker control. The easiest thing seems to be simply not binding it- handle passing the value of your object to the control and from the control to your object manually. A few lines of code will save you lots of headaches...

private void BindData()
{
    // can't bind the datetimepicker, so handle it manually...
    if (o.myDate == null)
    {
        dtDatePicker.Checked = false;
    }
    else
    {
        dtDatePicker.Checked = true;
        dtDatePicker.Value = o.myDate.Value;
    }
}

private void Save()
{
    if (dtDatePicker.Checked)
    {
        o.myDate = dtDatePicker.Value;
    }
    else
    {
        o.myDate = null;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文