简体   繁体   English

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

[英]how to set datetimepicker with null value if date not selected(c# winforms)

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 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 http://www.mofeel.net/70-microsoft-public-dotnet-framework-windowsforms/8806.aspx

DateTimePicker s 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 . DateTimePicker不能设置为null,因为DateTime不能为null,但您可以将它们设置为DateTime.MinValue ,这是未初始化的DateTime的默认值。 And then you just check if the dtp.Value = DateTime.MinValue and if so, treat it as null. 然后你只需检查dtp.Value = DateTime.MinValue是否如此,如果是,则将其视为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. 但是,如果你想真正区分何时没有选择任何值,最简单的方法是将DateTimePicker.ShowCheckBox设置为true,然后检查dtp.Checked ,如果是,则读取该值,否则将其视为空值。

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: 添加“CloseUp”或“ValueChanged”事件处理程序以重置用户操作的格式:

yourDTP.Format = DateTimePickerFormat.Short

I like the ShowCheckBox option. 我喜欢ShowCheckBox选项。 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: 然后,get和set代码如下所示:

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

The easiest way is to add a text box and set the visible property to false. 最简单的方法是添加一个文本框并将visible属性设置为false。 On the valuechanged event of the date picker populate the text box with the same date time value of the picker control. 在日期选择器的valuechanged事件上,使用选择器控件的相同日期时间值填充文本框。 Check the value of the text box if null string set the value to null. 如果null字符串将值设置为null,请检查文本框的值。

this is how i solved it. 这就是我解决它的方式。 I couldn't have NULLS so I defined 1/1/1980 12am as MYNULLDATE. 我不能拥有NULLS所以我将1/1/1980 12am定义为MYNULLDATE。 I used databinding on the text and value of the datetimepicker. 我在datetimepicker的文本和值上使用了数据绑定。 I did not use the checkbox in the datetimepicker. 我没有使用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. 它似乎触发valuechanged事件所以我只使用自定义并更改了自定义格式。 I used a flowpanel and a NONBOUND checkbox to sit in front of the datetimepicker. 我使用了flowpanel和NONBOUND复选框来坐在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 在非绑定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);
        }
    }

Using Vs 2015 and having no luck binding a DateTimePicker control. 使用Vs 2015并且没有运气绑定DateTimePicker控件。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM