C# DateTimePicker stuck in loop

2020-04-17 04:42发布

I have a datetimepicker in C#. When I click on it, it expands to show a monthly calendar, when I click the left arrow to go back a month, it changes the value and calls my event. The event includes too much code to include here but it calls several functions needless to say.
The problem I'm having is that when I click that left arrow it gets stuck in some sort of loop and keeps descending through the months and I can't stop it. One of the functions that is being called contains a Application.DoEvents() and if I comment that out it doesn't get stuck in the loop, but I need that command to update another section of the interface. Any idea why this is happening?

I can duplicate it sometimes with this code, sometimes it just does it a couple times, sometimes it gets stuck in the loop.

private void DateTimePickerValueChangedEvent(object sender, EventArgs e) 
{ 
afunction(); 
} 

private void afunction() 
{ 
listView1.Clear(); 
panel1.Visible = true; 
Application.DoEvents(); 
} 

4条回答
Deceive 欺骗
2楼-- · 2020-04-17 05:25

I also have the same problem. In my case, instead of calling DoEvents I'm updating a Crystal Report view. The only workaround I found is to update my view upon the CloseUp event instead of ValueChanged or TextChanged.

Scott, how did you finally corrected your problem ?

查看更多
虎瘦雄心在
3楼-- · 2020-04-17 05:25

The DateTimePicker ValueChanged event is buggy. Per Microsoft Windows Forms Team on this page https://connect.microsoft.com/VisualStudio/feedback/details/1290685/debugging-datetimepicker-event-hangs-vs:

"The DateTimePicker control installs a mouse hook as part of its functionality, but when the debugger has the WinForms application stopped on a breakpoint, it allows the possibility of a deadlock if VS happens to get a mouse message. For now, the deadlock is unfortunately a consequence of the DateTimePicker's design. The mouse hook is installed when the drop down is clicked to display the calendar. This means that breakpoints should not be sent in any event handlers which would be called while the calendar is active. We are currently investigating whether it is possible to address this issue and we will update this thread with further information if we are able to make a fix available."

查看更多
淡お忘
4楼-- · 2020-04-17 05:27

Without seeing any of the code, try these steps:

  1. Comment out the entire event handler to see how fast it runs with nothing attached to it.
  2. Uncomment lines one at a time to see which ones are causing the most problems.
  3. Analyze those method calls.
  4. ...
  5. Profit!
查看更多
来,给爷笑一个
5楼-- · 2020-04-17 05:29

You could try a couple of things. Get rid of the DoEvents inside of the ChangedEvent. Call the doevents inside of a seperate function after maybe a period of time (thread.sleep() ?).

I know doevents does cause issues but I rarely use it.

查看更多
登录 后发表回答