简体   繁体   中英

C# Textbox: Bind object to suggestion list

I am currently working at a project where I need to manage cities and their zip codes. Therefore, I created the fallowing object:

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

   ... further fields
}

and filled a List<Place> with a number of Place . Now I have a Textbox where I can enter the name of the city or its zip code. I both cases I would like to get a suggestion list which match with the entered input like this

Example: input = "1234" or "City"

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

If I than choose an item from this suggestion list I would like to get the related Place as a return value. How can I implement this feature in C# with a WindowsFormsApplication?

What you've asked isn't a simple or single question. I think you can have a hidden ListBox below the TextBox where the user will enter text.

Now TextBox has an event called OnTextChanged . This event is fired every time there is a change in the text. This means that this event is fired overtime a user adds or deletes a character in the corresponding TextBox.

You can use this event to filter the list to display in your ListBox.

Something like this

//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;
 }

Does this help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM