我有一个喜欢的TextChanged
活动ComboBox
;
private void comboBox1_TextChanged(object sender, EventArgs e)
{
foreach (var item in comboBox1.Items.Cast<string>().ToList())
{
comboBox1.Items.Remove(item);
}
foreach (string item in InputBox.AutoCompleteCustomSource.Cast<string>().Where(s => s.Contains(comboBox1.Text)).ToList())
{
comboBox1.Items.Add(item);
}
}
作为一个解释,当我改变组合框的文字,我想获得string
价值包含AutoCompleteCustomSource
在InputBox
(这是TextBox
)。
当我搜索它们时,它工作正常,但是当我选择该项目时,显然TextChanged
事件再次被触发,并且Text
属性Combobox
将重置。
如何解决呢?
如果我理解正确,那么我想您想隐藏组合框的TextChange事件。如果是,则可以创建一个由ComboBox继承的自定义控件,并覆盖TextChange事件。
public partial class MyCombo : ComboBox
{
public MyCombo()
{
InitializeComponent();
}
bool bFalse = false;
protected override void OnTextChanged(EventArgs e)
{
//Here you can handle the TextChange event if want to suppress it
//just place the base.OnTextChanged(e); line inside the condition
if (!bFalse)
base.OnTextChanged(e);
}
protected override void OnSelectionChangeCommitted(EventArgs e)
{
bFalse = true;
base.OnSelectionChangeCommitted(e);
}
protected override void OnTextUpdate(EventArgs e)
{
base.OnTextUpdate(e);
bFalse = false; //this event will be fire when user types anything. but, not when user selects item from the list.
}
}
编辑:另一个简单的方面是useTextUpdate
事件,而不是TextChange
保持组合框不变,而无需创建另一个自定义控件。
private void myCombo1_TextUpdate(object sender, EventArgs e)
{
foreach (var item in myCombo1.Items.Cast<string>().ToList())
{
myCombo1.Items.Remove(item);
}
foreach (string item in myCombo1.AutoCompleteCustomSource.Cast<string>().Where(s => s.Contains(myCombo1.Text)).ToList())
{
myCombo1.Items.Add(item);
}
}
TextUpdate
仅当用户在组合框中键入任何内容时,事件才会调用。但是,当用户从下拉列表中选择项目时,情况并非如此。因此,这不会激怒添加的项目。
如果您希望在两种情况下(上和下)都返回所有匹配项,也可以更改where条件。假设您在列表中有两个项目,1. Microsoft Sql Server, 2. microsoft office
那么如果我microsoft
仅键入内容将是什么结果。
Where(s => s.ToLower().Contains(comboBox1.Text.ToLower()))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句