我有一个绑定到对象列表的下拉列表。该列表可以有超过20000个项目。我不想立即填充列表。但是,当用户键入列表的文本部分时,控件应该开始过滤列表并显示匹配项。
我正在尝试以下方法:
private void cboName_TextChanged(object sender, EventArgs e)
{
var query1 = allNames.Where(x => x.firstname.Contains(cboName.Text) || x.lastname.Contains(cboName.Text)).ToList();
cboName.DataSource = query1;
cboName.ValueMember = "id";
cboName.DisplayMember = "firstname";
}
但它在性能方面不起作用。 有没有办法实现这个目标?
答案 0 :(得分:1)
根据您的要求,您可以试试这个
TextBox.AutoCompleteMode Property
示例:
private void Form1_Load(object sender, EventArgs e)
{
// Create the list to use as the custom source.
var source = new AutoCompleteStringCollection();
source.AddRange(new string[]
{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
});
// Create and initialize the text box.
var textBox = new TextBox
{
AutoCompleteCustomSource = source,
//Appends both Suggest and Append options.
AutoCompleteMode =
AutoCompleteMode.SuggestAppend,
AutoCompleteSource =
AutoCompleteSource.CustomSource,
Location = new Point(20, 20),
Width = ClientRectangle.Width - 40,
Visible = true
};
// Add the text box to the form.
Controls.Add(textBox);
}
答案 1 :(得分:0)
您可以坚持使用已有的代码。
private void cboName_TextChanged(object sender, EventArgs e)
{
var query1 = allNames.Where(x => x.firstname.Contains(cboName.Text) || x.lastname.Contains(cboName.Text)).ToList();
cboName.DataSource = query1;
cboName.ValueMember = "id";
cboName.DisplayMember = "firstname";
}
您可以在过滤前设置延迟,或者使用keydown
并聆听enter
密钥,然后过滤列表。