gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:04:27 24 4
gpt4 key购买 nike

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

最佳答案

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

但是,如果你想在没有选择值时真正区分,最简单的方法是将DateTimePicker.ShowCheckBox设置为true,然后检查dtp.Checked 如果为真,则读取该值,否则将其视为 null。

关于c# - 如果未选择日期,如何将 datetimepicker 设置为空值 (c# winforms),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com