Son*_*nül 2 c# combobox winforms
我有喜欢的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);
}
}
Run Code Online (Sandbox Code Playgroud)
作为一个解释,当我改变组合框的文字,我想获得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.
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
另一个简单的方法是使用TextUpdate事件而不是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);
}
}
Run Code Online (Sandbox Code Playgroud)
TextUpdate只有当用户在组合框中输入任何内容时,才会调用event.但是,当用户从下拉列表中选择项目时.所以,这不会重新添加添加的项目.
如果您希望在两种情况下(上部和下部)返回所有匹配的项目,也可以更改where条件.假设您在列表中有两个项目,1. Microsoft Sql Server, 2. microsoft office那么如果我microsoft只键入,结果会是什么.
Where(s => s.ToLower().Contains(comboBox1.Text.ToLower()))
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
3796 次 |
| 最近记录: |