How to add the SfAutocomplete control at runtime
SfAutoComplete controls provide a support to bind with different data source dynamically. We can add the data source during run time also.
To add Dynamic Data source in Autocomplete follow the below given procedure:
Step 1: Create the autocomplete sample with all necessary assemblies.
Step 2: Create an Observable collection where we have to store the data into it. Also create an instance of Observable collection. Set the instance of Observable collection to Autocomplete Data Source.
Step 3: Create a Button for adding new set of data. In which add new collection of data.
The below code illustrates the way to achieve this.
Code snippet:
namespace AutoComplete { public partial class AutoCompletePage : ContentPage { public ObservableCollection<Person> personCollection; SfAutoComplete autocomplete = new SfAutoComplete(); public AutoCompletePage() { //Initialize the autocomplete control SfAutoComplete autocomplete = new SfAutoComplete(); autocomplete.DisplayMemberPath = "Name"; autocomplete.SelectedValuePath = "Age"; autocomplete.MaximumDropDownHeight = 200; //Adding collections to the autocomplete. personCollection = new ObservableCollection<Person>(); personCollection.Add(new Person("Joes", 30)); personCollection.Add(new Person("Anita", 20)); personCollection.Add(new Person("Gorge", 40)); personCollection.Add(new Person("Jessy", 50)); personCollection.Add(new Person("Arya", 60)); autocomplete.DataSource = personCollection; Button button = new Button(); button.Text = " Add Data "; button.Clicked += new EventHandler(Button_Clicked); //Setting Layout for the autocomplete text box. StackLayout autocompleteLayout = new StackLayout(); autocompleteLayout.Children.Add(autocomplete); Content = autocompleteLayout; } public void Button_Clicked(object sender, EventArgs e) { personCollection.Add(new Person("James", 35)); personCollection.Add(new Person("Akbar", 25)); personCollection.Add(new Person("Gabriel", 25)); personCollection.Add(new Person("Jeff", 37)); personCollection.Add(new Person("Anderson", 29)); } public class Person : View { public Person(String _name, int _age) { this.Name = _name; this.Age = _age; } public String Name { get { return (String)GetValue(NameProperty); } set { SetValue(NameProperty, value); } } public static readonly BindableProperty NameProperty = BindableProperty.Create<Person, String>(p => p.Name, "", BindingMode.Default, null, null); public int Age { get { return (int)GetValue(AgeProperty); } set { SetValue(AgeProperty, value); } } public static readonly BindableProperty AgeProperty = BindableProperty.Create<Person, int>(p => p.Age, 22, BindingMode.Default, null, null); } } }
Image before the data source added dynamically:
Image to “ADD DATA” to the data source:
|
Image after Data Source get added: