tabbing out of control causes control that should be losing focus to regain it
I have a textbox.Leave event handler and now I can't tab out of the textbox (I can still click out).
This is how the event is added:
[...from the form...]
EKFG_Sig.Config.AutocompleteManager am = new EKFG_Sig.Config.AutocompleteManager(this.GetType().FullName);
foreach (Control c in this.Controls) {
if (c is TextBox) {
TextBox tb = (TextBox)c;
am.AddAutocomplete(tb);
}
}
[...from autocompleteManager...]
public void AddAutocomplete(TextBox control) {
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
DataTable dt = new DataTable("AutoComp开发者_StackOverflowlete");
dt.Columns.Add("Name");
dt.Columns.Add("Values");
try {
dt.ReadXml(getAutocompleteFile());
} catch (Exception) {
initialize();
}
DataRow[] values = dt.Select("Name = '" + Name + "." + control.Name + "'");
foreach (DataRow row in values) {
collection.Add(row[1].ToString());
}
control.AutoCompleteMode = AutoCompleteMode.Suggest;
control.AutoCompleteSource = AutoCompleteSource.CustomSource;
control.AutoCompleteCustomSource = collection;
control.Leave += Autocomplete_Leave;
}
private void Autocomplete_Leave(object sender, EventArgs args){
((TextBox)sender).AutoCompleteCustomSource.Add(((TextBox)sender).Text);
writeAutocomplete(Name + "." + ((TextBox)sender).Name, ((TextBox)sender).Text);
}
private static void writeAutocomplete(String name, String addition) {
DataTable dt = new DataTable("AutoComplete");
dt.Columns.Add("Name");
dt.Columns.Add("Values");
try {
dt.ReadXml(getAutocompleteFile());
} catch (Exception) {
initialize();
}
DataRow[] values = dt.Select("Name = '" + name + "'");
foreach (DataRow row in values) {
if (row[1].ToString() == addition) {
return;
}
}
dt.Rows.Add(new object[] { name, addition });
try {
dt.WriteXml(getAutocompleteFile());
} catch (IOException) {
System.Threading.Thread.Sleep(500);
try {
dt.WriteXml(getAutocompleteFile());
} catch (IOException) {
//failed to write. ignore
}
}
}
Any idea what's causing this problem and how can I fix it?
If I comment out ((TextBox)sender).AutoCompleteCustomSource.Add(((TextBox)sender).Text);
it works. Any idea why? And how can I keep this line and it still work?
Eyeballing the code, the only thing suspicious looking is the Thread.Sleep. Is it maybe hitting this every time and thereby making it appear to not be leaving?
Some other pointers if you haven't done any of these yet... Consider taking out your code and adding it in line by line/ block by block until you see the unexpected behavior. That will at least narrow it down for you.
Is something else attaching to the Leave event for the text boxes that's causing the grief?
Maybe set an event on the Enter event to see if it is a case of forcefully getting focus back and not a case of focus never leaving.
精彩评论