组合框自动完成键/值对
本文关键字:值对 组合 | 更新日期: 2023-09-27 17:54:31
我有一个组合框,代码如下:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
using (var service = WebServiceHelper.GetCoreService())
{
string physicianXml = service.SearchPhysicians(SessionInfo.Current.ClientCode, SessionInfo.Current.MachineName,
SessionInfo.Current.Username, comboBox1.Text);
var physicians = PhysicianItemList.FromXml(physicianXml);
AutoCompleteStringCollection autoCompleteStringCollection = new AutoCompleteStringCollection();
foreach (var physician in physicians.Items)
{
autoCompleteStringCollection.Add(physician.LastName + ", " + physician.FirstName);
}
comboBox1.AutoCompleteCustomSource = autoCompleteStringCollection;
comboBox1.Select(comboBox1.Text.Length, 0);
}
}
基本上,用户输入医生名字的前几个字符,它应该用前100个匹配记录填充自动完成列表。它工作得很好,但我需要将其关联回一个键(表中的PK或医师的NPI号)。似乎AutoCompleteStringCollection
不支持键。有谁能提出一个方法吗?表中大约有700万条记录,所以我不想预先填充ComboBox。
谢谢
当您构建AutoCompleteStringCollection
时,也为名称,id对构建Dictionary<String, int>
。然后使用一些事件(文本框验证或用户提交/保存点击)来查找和设置id。您可以将字典存储在文本框Tag
中。
编辑
出于某种原因,我以为你正在使用文本框控件。忘记AutoCompleteStringCollection
,只构建Dictionary<String, int>
。对于组合框,将autocompletesource设置为ListItems,设置组合框的显示名称和值,并将数据源设置为字典。
combobox.DisplayMember = "key";
combobox.ValueMember = "value";
combobox.AutocompleteSource = AutocompleteSource.ListItems;
combobox.DataSource = myDictionary;
但是,当用户在组合框中输入n个字符时,您应该只填充数据源并自动完成一次,否则会出现错误。我曾经尝试过将其用于动态自动完成(例如,如果用户清除文本并重新键入,则列表会清除),但我不得不忘记组合框,并使用混合文本框列表框方法,就像这个用户
看起来你的问题是AutoCompleteStringComplete是专门为字符串(因此,名称)。
你可能想看看父类(IList
, ICollection
, IEnumerable
),看看你是否可以自制一些针对键/值结构的模板。
太晚了,但也许有人会使用这个代码:
this.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
RNProveedor rnProveedor = new RNProveedor();
var listaProveedores = rnProveedor.Buscar();
Dictionary<int, String> dicTemp = new Dictionary<int, string>();
foreach (var entidad in listaProveedores)
{
dicTemp.Add(entidad.ProvNro, entidad.ProNombre);
}
this.DataSource = new BindingSource(dicTemp, null);
this.DisplayMember = "Value";
this.ValueMember = "Key";
和选择值
public int GetValorDecimal()
{
KeyValuePair<int, string> objeto = (KeyValuePair<int, string>)this.SelectedItem;
return objeto.Key;
}
在这个例子中,你不会遇到任何重复字符串的问题,就像上面的例子