问题
i am trying to implement my own ComboBox class in C# because, untill 3.5 NET Framework (if i'm not mistaking) suggestion lookup is made with a "StartWith" function (i.e. if the list contains "Doe, John" and user types "John", that item is not displayed). Basically i'm adding or removing items on text change event, getting them from the initial content of the list. Everything works pretty fine for what i am looking for, the only issue is, when ComboBox is clicked out, an item is still being selected even though it is not equal to the inserted text. Following the example i did, i want that "Doe, John" is selected (and set as ComboBox.Text property) only if user clicked on it, if user just typed "John" and no item is strictly equal to it (not just contain it), then Text property must remain as the user inserted it. Here's the code of my derived class
public class customTB : ComboBox
{
private object[] startlist;
public customTB() : base()
{
this.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.None;
this.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.None;
this.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDown;
this.Sorted = true;
this.KeyPress += customTB_KeyPress;
this.TextChanged += customTB_TextChanged;
this.Enter += customTB_Enter;
}
void customTB_Enter(object sender, EventArgs e)
{
this.DroppedDown = (this.Items.Count > 0);
}
void customTB_TextChanged(object sender, EventArgs e)
{
UpdateList();
}
void customTB_KeyPress(object sender, KeyPressEventArgs e)
{
this.DroppedDown = (this.Items.Count>0);
}
void UpdateList()
{
if (this.startlist == null)
{
//get starting lists elems
this.startlist = new Object[this.Items.Count];
this.Items.CopyTo(this.startlist, 0);
}
this.BeginUpdate();
foreach (object o in startlist)
{
if (o.ToString().Contains(this.Text))
{
if (!this.Items.Contains(o))
this.Items.Add(o);
}
else if (this.Items.Contains(o))
this.Items.Remove(o);
}
this.EndUpdate();
}
}
If tried, any time you try to exit the ComboBox, Text is highlighted and its value is set to an item. As example of what i would like to have is: items contains "Doe John", "Smith John", "Smith Marie". if user types "John", then dropdown items are "Doe John" and "Smith John" but if he doesn't click any of the dropdown elements and exit the ComboBox (i.e. clicking outside), the Text remains "John"
回答1:
Have one boolean variable itemClicked
- Set itemClicked to false inside Enter event handler
- Set itemClicked to true inside SelectionChangeCommitted event handler
- Set Text property to string.Empty if not itemClicked inside DropDownClosed event handler
来源:https://stackoverflow.com/questions/39924888/c-sharp-preventing-custom-combobox-from-autoselecting-an-item