如果日期时间大于今天的日期,我尝试更改datetimepicker值。
我尝试在值更改后编写一个方法,它改变了值,但它正在进行循环,因为我将日期值更改为今天的日期。
如何修复此方法?
(如果if的答案为真,那么循环就会发生,当dateTimePickerUntil
值发生变化时,会在方法上重复)
private void dateTimePickerUntil_ValueChanged(object sender, EventArgs e)
{
MessageBox.Show(dateTimePickerUntil.Value.ToString());
if(dateTimePickerUntil.Value > DateTime.Now.Date)
{
dateTimePickerUntil.Value = DateTime.Now.Date;
untildate = Convert.ToDateTime(dateTimePickerUntil.Value.ToShortDateString());
}
else
{
untildate = Convert.ToDateTime(dateTimePickerUntil.Value.ToShortDateString());
}
}
答案 0 :(得分:0)
打破循环:您只需要检查dateTimePickerUntil.Value
untildate != dateTimePickerUntil.Value
。诀窍是首先更改untildate
,以便untildate
在下一个ValueChanged
事件发生之前已经包含正确的值。
private void dateTimePickerUntil_ValueChanged(object sender, EventArgs e)
{
if (dateTimePickerUntil.Value != untildate)
{
MessageBox.Show(dateTimePickerUntil.Value.ToString());
if (dateTimePickerUntil.Value > DateTime.Today)
{
untildate = DateTime.Today; // Set first, so we can compare on the next event.
dateTimePickerUntil.Value = DateTime.Today;
}
else
{
untildate = dateTimePickerUntil.Value;
}
}
}