C#文本框:将对象绑定到建议列表

时间:2017-11-15 09:35:09

标签: c# winforms textbox autosuggest

我目前正在一个需要管理城市及其邮政编码的项目中工作。因此,我创建了一个休闲对象:

class Place
{
   Guid Id { get; set; }
   string Name { get; set; }
   int ZipCode { get; set; }

   ... further fields
}

并填充List<Place>Place。现在我有一个Textbox,我可以输入城市名称或邮政编码。在这两种情况下,我想获得一个与输入的输入匹配的建议列表,如此

示例:input =&#34; 1234&#34;或&#34;城市&#34;

  • 12341 CityOne
  • 12342 CityTwo
  • 12343 CityThree
  • ...

如果我选择此建议列表中的某个项目,我希望将相关的Place作为返回值。如何使用WindowsFormsApplication在C#中实现此功能?

1 个答案:

答案 0 :(得分:0)

您所问的不是一个简单或单一的问题。我想你可以在TextBox下面有一个隐藏的ListBox,用户将在其中输入文字。

现在TextBox有一个名为OnTextChanged的事件。每次文本发生变化时都会触发此事件。这意味着用户在相应的TextBox中添加或删除字符时会超时触发此事件。

您可以使用此事件过滤列表以显示在ListBox中。

像这样的东西

//Imagine the TextBox ID as CityZipTextBox and ListBox ID as CityZipSuggestionsListBox
protected override void OnTextChanged(EventArgs e)
{
    string txtCityZip = CityZipTextBox.Text;
    List<Place> suggestedPlaces = filterCode;//Code to filter the full list using the TextBox content
    CityZipSuggestionsListBox.DataSource = suggestedPlaces;
 }

这有帮助吗?

相关问题