Search code examples
c#comboboxwindows-store-apps

How can I set the search option in combobox C#


I have combobox with country names I want to set search box to that to easily find the country how can I do that?

Here is my XAML coding of ComboBox

<ComboBox x:Name="countryComboBox" Loaded="countryComboBox_Loaded" Width="300"/>

here is C# coding

private void countryComboBox_Loaded(object sender, RoutedEventArgs e)
{
       countryComboBox.ItemsSource = GetCountries();            
}

Countries list is loading but no text area and I want to add it to easily find the country.


Solution

  • Something like this (may have compile errors, i write the code in Notepad not VS)

    <StackPanel>
        <TextBox x:Name="searchBox" TextChanged="searchBox_TextChanged" />
        <ComboBox x:Name="countryComboBox" Loaded="countryComboBox_Loaded" Width="300"/>
    </StackPanel>
    
    List<string> countries;
    private void countryComboBox_Loaded(object sender, RoutedEventArgs e)
    {
       countries = GetCountries();
       countryComboBox.ItemsSource = countries;           
    }
    
    private void searchBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (searchBox.Text == "") return;
    
        int index = countries.FindIndex((str) => str.StartsWith(searchBox.Text));
        if (index != -1)
            countryComboBox.SelectedIndex = index;
    }