Remove from the database the selected record in the Listvew (Using Entity Framework)

1

Continuing with the example of Listview show two fields in each row

Visual Studio Community 2015 + SQLite + Entity Framework

The database has 2 fields: ID and ShipType

Class for mapping the database:

namespace ImperialFleet
{
public class ShipTypeClass
{
    private string id;
    private string type;

    public ShipTypeClass(string id, string type)
    {
        this.Id = id;
        this.ShipType = type;
    }

    public string Id { get; set; }
    public string ShipType { get; set; }
}
}

Code to load the Listview

        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();

       }

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

xaml Listview

<ListView x:Name="listView" HorizontalAlignment="Left" Height="198" Margin="39,10,0,0" VerticalAlignment="Top" Width="446">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Id" Width="Auto" 
                        DisplayMemberBinding="{Binding Id}"/>

                <GridViewColumn Header="Tipo nave" Width="Auto" 
                        DisplayMemberBinding="{Binding ShipType}"/>
            </GridView>
        </ListView.View>
    </ListView>

I do not know how to take the Id (which is unique in the database) of the selected record in the listview and then delete it from the database, if I have to generate a new instance with the object to delete or if you just need to reference it by your ID in some way

I guess it will be something like that

            using (var db = new ImperialFleetDBEntities())
        {

            db.ShipsType.Remove(IDdelItemABorrar);
            db.SaveChanges();
    }

but I do not know how to "take" IDdelItemABorrar from the Listview

    
asked by fedeteka 20.11.2017 в 15:00
source

3 answers

0

Solution:

        private void button2_Click(object sender, RoutedEventArgs e)
    {

        var ShipSelected = (ShipsType)listView.SelectedItems[0];
        using (var db = new ImperialFleetDBEntities())

        {
            db.ShipsType.Attach(ShipSelected);
            db.ShipsType.Remove(ShipSelected);
            db.SaveChanges();

            //Refrescar la lista de barcos
            listView.ItemsSource = db.ShipsType.ToList();
        }

    }
    
answered by 25.11.2017 / 05:50
source
2

If you are using a Model behind the View you can use the SelectedItem property, to recover the selected element, I recommend you use the MVVM so you can do these things easier without reloading the Code Behind. Greetings

    <ListView x:Name="listView" ItemsSource="{Binding ShipList}" SelectedItem="{Binding Path=SelectShip}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Id" Width="Auto" 
                                DisplayMemberBinding="{Binding Id}"/>

                <GridViewColumn Header="Tipo nave" Width="Auto" 
                                DisplayMemberBinding="{Binding ShipType}"/>
            </GridView>
        </ListView.View>
    </ListView>

Model / ViewModel / Code behind:

   private ObservableCollection<ShipTypeClass> _shipList;
    private ShipTypeClass _selectShip;

    public ObservableCollection<ShipTypeClass> ShipList
    {
        get { return _shipList; }
        set { _shipList = value; this.OnPropertyChanged(nameof(ShipList));}
    }

    public ShipTypeClass SelectShip
    {
        get { return _selectShip; }
        set { _selectShip = value; this.OnPropertyChanged(nameof(SelectShip)); }
    }

   private void CargarLista()
    {
        List<ShipTypeClass> listTmp = new List<ShipTypeClass>();
        using (var db = new ImperialFleetDBEntities())
        {

            listTmp = db.ShipsType;

        }

        ShipList.Clear();
        foreach (var str in listTmp)
        {
            ShipList.Add(str);
        }
    }

and within a button or any routine that you have to confirm that you want to delete you just have to do:

    public void EliminarRegistro()
    {
        var entity = this.GetById(SelectShip.Id); 

// we get the object, if you want to check that it still exists in database you can pass the ID; On the contrary you can directly pass the SelectShip selector  instead of entity.

        if (entity != null)
        {
            using (var db = new ImperialFleetDBEntities())
            {
                // eliminamos el registro
                db.ShipsType.Remove(entity);
                db.SaveChanges();
            }
        }
    }
    
answered by 20.11.2017 в 15:46
1

You can assign the reference of the object to the property Tag of the GridView, binding it with Binding :

    

    <!--Le asignamos el objeto a la propiedad Tag, -->
    <GridView Tag="{Binding Path=.}">

        <GridViewColumn Header="Id" Width="Auto" 
                DisplayMemberBinding="{Binding Id}"/>

        <GridViewColumn Header="Tipo nave" Width="Auto" 
                DisplayMemberBinding="{Binding ShipType}"/>
    </GridView>
</ListView.View>

Tag="{Binding Path=.}" means that Tag would be equal to the assigned object in ItemsSource , in this case, ShipType .

Now in the delegate listView_SelectionChanged we verify if the selected element is a GridView and if it is, we castrate the value of the property Tag to the type assigned to it in the binding:

private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var item = listView.SelectedItem as GridView;

    if(item != null)
    {
        ShipType ship = item.Tag as ShipType; // obtenemos el objeto asignado al tag.

        using (var db = new ImperialFleetDBEntities())
        {
            // eliminamos el registro
            db.ShipsType.Remove(ship);
            db.SaveChanges();
        }
    }
}
    
answered by 20.11.2017 в 15:24