简体   繁体   中英

C# - SQlite + Entity - Show items on a ListView

Using Visual Studio 2015 and learning ORM with SQlite + Entity (WPF application)

My database with fields: ID and ShipType

I can populate a listView with the ShypType field:

    private void button_Click(object sender, RoutedEventArgs e)
    {
        List<string> shipList = new List<string>();
        using (var db = new ImperialFleetDBEntities())
        {
            shipList = (from g in db.ShipsType select g.ShipType).ToList();
            db.Dispose();
        }

        listView.Items.Clear();                   
        foreach (string str in shipList)
        {
            listView.Items.Add(str);
        }

    }

But I can't figure how to also diplay the ID field (g.ID on this example)

In this link C# ListView Display the solution is using ListViewSubItems

But If I type listView. I don't have any SubItems option

The solution is 5 years old, maybe that's de problem??

The simplest way would probably be:

private void button_Click(object sender, RoutedEventArgs e)
{
    using (var db = new ImperialFleetDBEntities())
    {
        listView.Items.Clear();
        foreach(var item in (from g in db.ShipsType select new { ID = g.ID, ShipType = g.ShipType }))
        {
            listView.Items.Add(item)
        }
    }
}

This should populate your listView in correct way and make sure these new objects won't be tracked by EF.

If you'd like, you could create full class, like ViewModel for listView containing fields you need and then select to them like:

foreach(var item in (from g in db.ShipsType select new NewShipType { ID = g.ID, ShipType = g.ShipType }))
{
    listView.Items.Add(item)
}

or using constructor (if you make one).

With seprate ViewModel you can of course use in-between list object and clear and add them to listView.Items, which is impossible with anonymous object.

By the way, you don't have, and maybe you shouldn't write db.Dispose() inside using clause, as using is exactly meant to make sure the object inside is disposed - you cannot use using on object that is not implementing IDisposable interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM