要设置支持自动完成的控件,必须指定自动完成功能的来源。当使用设置为字符串集合时自动完成自定义源财产,自动完成源属性必须设置为自动完成源.自定义源 and 自动完成模式设置为AutoCompleteMode.SuggestAppend
or AutoCompleteMode.Suggest
.
这些属性必须一起使用指定自动完成功能的工作方式。
因为问题中的代码似乎正在使用某种数据源来创建AutoCompleteCustomSource
集合,这是一个创建一个通用示例CustomSource
from a List<class>
,使用 a 将绑定添加到控件Binding
类并使用更新一些控件的值BindingSource
.
该示例(如视觉示例所示)使用三个控件:一个 TextBox (txtAutoComp
),其中启用了自动完成功能,以及两个标签(lblNickName
and lblNickValue
),绑定到同一数据源,当 AutoComple 控件的文本更改时更新。
自动完成功能已扩展为允许使用部分字符串查找元素,只需单击按钮 (btnFindNick
,此处)或按Enter
在文本框中键入:
private class NickName
{
public string Nick { get; set; }
public int Value { get; set; }
}
private BindingSource source = null;
private List<NickName> NickNames = null;
private void Form1_Load(object sender, EventArgs e)
{
NickNames = new List<NickName>();
NickNames.AddRange(new[] {
new NickName() { Nick = "", Value = 0 },
new NickName() { Nick = "Andrea", Value = 10 },
new NickName() { Nick = "Arnold", Value = 20 },
new NickName() { Nick = "Barbara", Value = 30 },
new NickName() { Nick = "Billy", Value = 40 },
new NickName() { Nick = "Clint", Value = 50 },
new NickName() { Nick = "Cindy", Value = 60 },
});
source = new BindingSource();
source.DataSource = NickNames;
txtAutoComp.AutoCompleteMode = AutoCompleteMode.Suggest;
txtAutoComp.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtAutoComp.AutoCompleteCustomSource.AddRange(NickNames.Select(n => n.Nick).ToArray());
Binding textBind = new Binding("Text", source, "Nick", true, DataSourceUpdateMode.OnPropertyChanged);
textBind.Parse += (s, evt) => {
source.CurrencyManager.Position = NickNames.FindIndex(1, r => r.Nick.Equals(evt.Value));
};
txtAutoComp.DataBindings.Add(textBind);
lblNickName.DataBindings.Add(new Binding("Text", source, "Nick"));
lblNickValue.DataBindings.Add(new Binding("Text", source, "Value"));
}
private void btnFindNick_Click(object sender, EventArgs e)
{
FindNick(txtAutoComp.Text);
}
private void txtAutoComp_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) {
e.SuppressKeyPress = true;
FindNick(txtAutoComp.Text);
}
}
void FindNick(string partialName)
=> this.source.CurrencyManager.Position = NickNames.FindIndex(
1, r => r.Nick.Contains(partialName)
);