My client wanted to have a textbox in the Customer form of the application, which offers the applicable endings to a started street name. He starts to type a street name and the textbox offers a list of streets which start with the char sequence he typed into the textbox.
I said to myself: thats okay, textboxes have the AutoCompleteCustomSource property and even though a list of common street names will be longer than it could be pre-filled on start, i could just hit a database with a query, populate an AutoCompleteStringCollection and show that to the user.
Now here's the thing: if I make the list populate on every keypress/keydown whatever, the program crashes and throws an AccessViolationException.
I've found out that that's because:
The control is in the middle of showing the AutoComplete list when at the same time it is being modified, resulting in the crash.
When you refresh the Autocomplete List, the control is recreated with new pointers. Keyboard and mouse events (KeyPress, MouseOver, MouseLeave, MouseHover) attempt to reference the old control's pointers which are now invalid in memory causing a memory access violation to occur.
The underlying AutoComplete implementation does not allow for changing the AutoComplete candidate list object once it has been set on a window. To allow changing the list, WinForms destroys the Edit control or ComboBox and recreates it. This causes an exception if the underlying control is destroyed while the AutoComplete window is still use it.
I read about this on MSDN, their resolution:
Do not modify the AutoComplete candidate list dynamically during key events.
I've also tried everything from this thread
So how could I make this work, if I insist on offering the applicable street names keypress-by-keypress?
Note: I know that you can do this by creating a custom control and such, but can it be done with just pure coding wizardry?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…