Search code examples
c#xamarinxamarin.formspicker

How can I make a Picker display options based on a table in a SQLite DB table?


Im getting values from an api and storing them in a table using the following method. I would like to retrieve the items and use them as options in a Picker. The code implementation for the class, method and picker are below. What method can i write for the SelectedIndexChanged such that it shows the items?

//class
public class Items
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string ItemsVariety { get; set; }
    }
}

//method retrieving items and storing them in a SQLite DB
private async Task GetItems()
        {
            var address = App.Server + "GetItems";
            HttpClient client = new HttpClient();
            var response = await client.GetStringAsync(address);
            List<Items> varieties = JsonConvert.DeserializeObject<List<Items>>(response);
            List<Items> varieties1 = new List<Items>();
            Items item = new Items();
             
            foreach (var i in varieties)
            {
                item.ItemsVariety = item.ItemsVariety;
                varieties1.Add(i);
                await App.dBModel.SaveItems(i);
            }
        }

//Code for Picker

 <Picker x:Name="MyItems" SelectedIndexChanged="MyItemsChanged"/>

Solution

  • Get the list from the SQLite database first. It seems you save the json values to SQLite databse. If you receive the data from the database. You could try the code below. You could get more details via downloading source file from the link below. https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/getstarted-notes-database/

    _database.Table<Items>().ToListAsync();  //If you use the dBModel as you database, replace the _database with your own database.
    

    Binding the list of sqlite database to ItemsSource.

     MyItems.ItemsSource = _database.Table<Items>().ToListAsync(); //
    

    Then set the ItemDisplayBinding which you want to display in Picker of database model.

    <Picker
            x:Name="MyItems"
            ItemDisplayBinding="{Binding ItemsVariety}"
            SelectedIndexChanged="MyItemsChanged" />