I’m using an AutoCompleteCustomSource for a TextBox in Append auto-complete mode. This works as expected; however, when an auto-complete suggestion appears, I still need access to just the text that the user entered. That is, when a suggestion appears, the Text property of the TextBox will return the suggestion.
Is there a way to also retrieve just the user typed string?
Update: One of my restrictions is that I must use the Append auto-complete mode.
There doesn’t appear to be a simple mechanism to retrieve only the user entered data and after trying to solve this problem, I can understand why. What constitutes user entered data is not always clear and it seems that Microsoft has decided to not tackle that question.
I’ve decided to manually keep track of the user data by registering for a
TextChangedevent. Since each key stroke will trigger this event, by keeping track of the previous value ofText, I can determine if either an Append auto-complete or paste operation has occurred.The code snippet below if from the
TextChangedevent handler of my customTextBoxclass;UserTextcontains the user entered data (of typestring).UpdateUserText(string)first determines if a change has occurred, and if so, assigns the new value toUserTextand issues an event. In the case of a paste operation, one could use the solution posted here; however, I opted to do the following:In this way, if text in the
TextBoxis no longer highlighted, then I assume it has become user entered text. This takes care of the paste operation (either via the keyboard or mouse) and caters for the user pressing the arrow keys in attempt to accept the auto-complete suggestion.One of the edge cases that I decided to ignore is when the user has typed the entire word but the last character, in this case I would not be able to differentiate between the auto-complete suggestion and the user input.
I also considered using a
StringBuilderto manually keep track of the user entered data but I think that requires more effort than keeping track of the already constructedstringinText.I’m always open to a better implementation if anyone has a suggestion 🙂