N. Smeding
N. Smeding

Reputation: 394

Getting specified data out of sqlite database with function?

I am trying to get a ListView with the names of each item inside the database but all I get back is the full table name. And if it is possible I want to use the same function to get other info like id later. If more information is needed ask me.

This is my code:

calling the function:

var categories = App.Database.GetCategoryByMenuID(1);
listView.ItemsSource = categories;

function:

public List<Categories> GetCategoryByMenuID(int menuID)
{
    return db.Table<Categories>().Where(x => x.Menu_ID == menuID).ToList();
}

table:

public class Categories
{
    public Categories()
    {
    }

    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public int Menu_ID { get; set; }
    public string Name { get; set; }
}

thank you in advance,

Upvotes: 0

Views: 91

Answers (1)

476rick
476rick

Reputation: 2795

Your var categories is a List filled with multiple Categories. The ListView prints the name of the object in every row, which is: Categories.

You should make your own datatemplate that prints the attribute name of each "Categories".

Declare your own DataTemplate like this:

var datatemplate = new DataTemplate(() =>
{
   var nameLabel = new Label();
   nameLabel.SetBinding(Label.TextProperty, "Name");

   return new ViewCell { View = nameLabel };
}

Next up use your datatemplate to show the name of the categories. Instantiate your ListView like this:

var listView = new ListView
{
     ItemsSource = categories,
     ItemTemplate = datatemplate
}

Then your ListView will show the names.

Upvotes: 1

Related Questions