2017-04-03 122 views
0

如果日期時間大於今天的日期,我試圖更改datetimepicker值。如何更改ValueChanged事件處理程序中的DateTimePicker的值

我試圖在值更改後編寫一個方法,它改變了值,但是由於我將日期值更改爲今天的日期,所以它正在形成一個循環。

我該如何解決這個問題?

(循環發生,如果如果當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()); 
    } 
} 
+1

好吧,沒關係。只需刪除無用的MessageBox.Show()調用。 –

+0

我知道仍然有效,但它不是正確的方法 – Nadav

回答

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;     
     } 
    } 
} 
相關問題