Google-Powered Autocomplete: Leveraging Search Suggestions in .NET MAUI
Tags: dotnetmaui, mobile, ui, google
Published: 2023-05-24 13:12:38

---
title: Google-Powered Autocomplete: Leveraging Search Suggestions in .NET MAUI
published: true
date: 2023-05-24 11:35:04 UTC
tags: dotnetmaui, mobile, ui, google
canonical_url: https://www.syncfusion.com/blogs/post/google-powered-autocomplete-dotnet-maui.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2vexuiu3nb796ywzv9cb.png
---
In this walkthrough, we will explore the custom filtering support provided by [Syncfusion’s Autocomplete control](https://www.syncfusion.com/maui-controls/maui-autocomplete#:~:text=The.NET%20MAUI%20Autocomplete%20control%20is%20highly%20optimized%20to,input%20view%20with%20the%20text%20and%20clear%20button. ".NET MAUI Autocomplete"). The Autocomplete control was designed to give users possible matches as they type, and it comes with a range of features such as different suggestion modes and custom search.

Using the custom filter support, we can create a Google search experience where suggestions are filtered based on user input.

This blog will guide you through the steps to achieve this behavior. By implementing this custom filtering feature, you can provide your users with more accurate and relevant search suggestions that enhance their overall experience. So, let’s learn how to utilize this feature of Autocomplete control in a .NET MAUI app.

## How to add the Syncfusion control

First, we’ll incorporate the Autocomplete control and associate data with it.

### Step 1: Add the .NET MAUI Autocomplete reference

Syncfusion’s [.NET MAUI controls](https://www.syncfusion.com/maui-controls ".NET MAUI controls") are available on [NuGet.org](https://www.nuget.org/ "NuGet Gallery"). To add the .NET MAUI Autocomplete to your project, open the [NuGet package manager](https://www.nuget.org/packages/ "NuGet Package Manager") in [Visual Studio](https://visualstudio.microsoft.com/ "Visual Studio"), search for [Syncfusion.Maui.Inputs](https://www.nuget.org/packages/Syncfusion.Maui.Inputs/ "Syncfusion.Maui.Inputs NuGet Package") , and then install it.

### Step 2: Handler registration

In the **MauiProgram.cs file** , register the handler for the Syncfusion core.

```csharp
using Microsoft.Extensions.Logging;

using Syncfusion.Maui.Core.Hosting;

namespace GoogleSearchDemo;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
	var builder = MauiApp.CreateBuilder();
	builder
	  .ConfigureSyncfusionCore()
	  .UseMauiApp<App>()
	  .ConfigureFonts(fonts =>
	  {
	     fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
	     fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
	  });

          #if DEBUG
	  builder.Logging.AddDebug();
          #endif
	  return builder.Build();
    }
}
```

### Step 3: Include the namespace

After adding the NuGet package to the project, as discussed in the previous reference section, add the XML namespace to the **MainPage.xaml** file, as shown in the following code example.

```xml
xmlns:editors="clr-namespace:Syncfusion.Maui.Inputs;assembly=Syncfusion.Maui.Inputs"
```

### Step 4: Add the Autocomplete control

Add the Autocomplete control inside a grid. Also, customize the Autocomplete control with these properties:

- **Placeholder:** Displays a text hint inside the control before the user inputs any value.
- **MaxDropDownHeight** : Maximum height of the dropdown list that appears when it gets opened.
- **TextSearchMode:** Sets the search mode for matching items in the Autocomplete control’s data source. This property is set to **Contains** , meaning the control will show all items containing the typed text.
- **WidthRequest** and **HeightRequest** : These properties set the preferred width and height of the control.

```xml
<Grid Margin="0,20,0,0">
 <editors:SfAutocomplete HeightRequest="50"
                         Placeholder="Search something" MaxDropDownHeight="250"
                         TextSearchMode="Contains"
                         WidthRequest="300">
 </editors:SfAutocomplete>
</Grid>
```

### Step 5: Set custom filtering class

The Autocomplete control supports applying custom filter logic to suggest items based on your filter criteria using the **FilterBehavior** and **SearchBehavior** properties. The default value of **FilterBehavior** and **SearchBehavior** is null. Here, the **FilterBehavior** is set to **CustomFiltering**. Creation of the **CustomFiltering** class is explained in the upcoming section.

```xml
<Grid Margin="0,20,0,0">
 <editors:SfAutocomplete HeightRequest="50"
                         Placeholder="Search something" MaxDropDownHeight="250"
                         TextSearchMode="Contains"
                         WidthRequest="300">
  <editors:SfAutocomplete.FilterBehavior>
   <local:CustomFiltering/>
  </editors:SfAutocomplete.FilterBehavior>
 </editors:SfAutocomplete>
</Grid>
```

With this, the UI part is completely implemented. Let’s focus on the backend where the **CustomFiltering** class is implemented.

## Creating the CustomFiltering class

Next, let’s create a Google-like suggestion filter using the custom filter property of the [.NET MAUI Autocomplete control](https://www.syncfusion.com/maui-controls/maui-autocomplete#:~:text=The.NET%20MAUI%20Autocomplete%20control%20is%20highly%20optimized%20to,input%20view%20with%20the%20text%20and%20clear%20button. ".NET MAUI Autocomplete").

### Step 1: Create a custom class

Create a class named **CustomFiltering** and import the [Syncfusion.Maui.Inputs](https://www.nuget.org/packages/Syncfusion.Maui.Inputs/ "Syncfusion.Maui.Inputs NuGet Package") namespace, which provides classes and interfaces for the Autocomplete control.

```csharp
using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo
{
    public class CustomFiltering
    {
    }
}
```

### Step 2: Implement the interface

Implement the interface **IAutocompleteFilterBehavior** in the **CustomFiltering** class. This interface defines the filtering behavior for the control. The first step is to import the necessary namespaces required for the code to execute.

```csharp
using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo : IAutocompleteFilterBehavior
{
    public class CustomFiltering
    {
    }
}
```

### Step 3: Customize the constructor method

Define a constructor method, which is called when an instance of the **CustomFiltering** class is created. In the constructor, call the **GetGoogleSuggestions** method with the initial search term **test**.

```csharp
using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo
{
    public class CustomFiltering : IAutocompleteFilterBehavior
    {
        public CustomFiltering()
        {
            GetGoogleSuggestions("test");
        }
    }
}
```

### Step 4: Define the filtering method from IAutocompleteFilterBehavior

Define the **GetMatchingItemsAsync** method, which is responsible for filtering the data for the Autocomplete control. It takes two arguments: the [SfAutocomplete](https://help.syncfusion.com/maui/autocomplete/getting-started "Getting started with .NET MAUI Autocomplete control") class’s source object and an instance of the **AutocompleteFilterInfo** class. The **AutocompleteFilterInfo** class contains the current filter text entered by the user.

```csharp
using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo
{
    public class CustomFiltering : IAutocompleteFilterBehavior
    {
        public CustomFiltering()
        {
            GetGoogleSuggestions("test");
        }

        public Task<object> GetMatchingItemsAsync(SfAutocomplete source, AutocompleteFilterInfo filterInfo)
        {
            return GetGoogleSuggestions(filterInfo.Text);
        }

    }
}
```

### Step 5: Define a method to get Google suggestions

Define a private, asynchronous method named **[GetGoogleSuggestions](https://www.npmjs.com/package/get-google-suggestions "get-google-suggestions NPM Package")**, which makes a web request to the Google search suggestions API to fetch suggestions for the given query.

It takes a string parameter **query** as input and returns a list of suggestions as an object. It uses the **HttpClient** class to make the web request and parses the XML response to extract the suggestions.

```csharp
using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo
{
    public class CustomFiltering : IAutocompleteFilterBehavior
    {
        public CustomFiltering()
        {
            GetGoogleSuggestions("test");
        }

        public Task<object> GetMatchingItemsAsync(SfAutocomplete source, AutocompleteFilterInfo filterInfo)
        {
            return GetGoogleSuggestions(filterInfo.Text);
        }

        private async Task<object> GetGoogleSuggestions(string query)
        {
            if (string.IsNullOrEmpty(query) || string.IsNullOrWhiteSpace(query))
            {
                return new List<string>();
            }

            string xmlSuggestions;

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var searchQuery = String.Format("https://www.google.com/complete/search?output=toolbar&q={0}", query);
                    xmlSuggestions = await client.GetStringAsync(searchQuery);
                }
                catch
                {
                    return null;
                }
            }

            XDocument doc = XDocument.Parse(xmlSuggestions);
            var suggestions = doc.Descendants("CompleteSuggestion")
                                 .Select(
                                    item => item.Element("suggestion").Attribute("data").Value);

            return suggestions.ToList();
        }
    }
}
```
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/Output-suggestions-similar-to-those-found-on-Google.gif" alt="Output suggestions similar to those found on Google" style="width:100%">

  <figcaption>Output suggestions similar to those found on Google</figcaption>

</figure>

## GitHub reference

For more information, refer to the [demo on GitHub](https://github.com/SyncfusionExamples/maui-general-samples/tree/main/GoogleSearchDemo "Google-Powered Autocomplete in .NET MAUI GitHub demo").

## Conclusion

Thank you for taking the time to read this blog post. In this article, we have discussed the necessary steps to display Google search suggestions in our [.NET MAUI Autocomplete](https://www.syncfusion.com/maui-controls/maui-autocomplete ".NET MAUI Autocomplete") control with custom filtering support. We recommend exploring the [Getting Started documentation](https://help.syncfusion.com/maui/autocomplete/getting-started "Getting started with .NET MAUI Autocomplete"). We hope you found this information helpful.

If you are an existing Syncfusion customer, the new version of [Essential Studio](https://www.syncfusion.com/forums/181344/essential-studio-2023-volume-1-main-release-v21-1-35-is-available-for-download "Essential Studio 2023 Volume 1") is available for download from the [License and Downloads](https://www.syncfusion.com/account/login "Essential Studio license and downloads page") page. For those who are not yet Syncfusion customers, we offer a 30-day [free trial](https://www.syncfusion.com/downloads "Free evaluation of the Essential Studio Products") to explore our available features.

Please let us know in the comments section below if you have any specific feature requests for our .NET MAUI controls. Additionally, you can contact us for assistance through our [support forums](https://www.syncfusion.com/forums "Syncfusion Support Forum"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/maui "Syncfusion Feedback Portal"). We are always happy to help you!

## Related blogs

- [Data Visualization with a Heat Map Using .NET MAUI Scheduler](https://www.syncfusion.com/blogs/post/heat-map-dotnet-maui-scheduler.aspx "Blog: Data Visualization with a Heat Map Using .NET MAUI Scheduler")
- [Chart of the Week: Creating a .NET MAUI Column Chart to Visualize Yearly Box Office Data](https://www.syncfusion.com/blogs/post/dotnet-maui-column-chart-visualize-yearly-box-office-data.aspx "Blog: Chart of the Week: Creating a .NET MAUI Column Chart to Visualize Yearly Box Office Data")
- [Create and Validate a Login Form in .NET MAUI](https://www.syncfusion.com/blogs/post/login-form-in-net-maui.aspx "Blog: Create and Validate a Login Form in .NET MAUI")
- [Elevate Your App’s User Experience with the New .NET MAUI Shimmer Control](https://www.syncfusion.com/blogs/post/dotnet-maui-shimmer-control.aspx "Blog: Elevate Your App’s User Experience with the New .NET MAUI Shimmer Control")