简体   繁体   中英

Items in database sqlite are not updating (Xamarin.Forms)

I am using Xamarin.Forms in visual studio and I have a list of products that I insert in a table. When I try to update the Cantidad, Precio or other feature, the Articulo don´t update and the list appears as it was before. I´m trying to use the PK as a string so when I try to update a item I need the Producto of the Articulo, it verify that the Id of the Producto exist in the database and then update.

This is my Model Articulo.cs

using SQLite;
using System;
using System.Collections.Generic;
using System.Text;

namespace Saansa.Modelos
{
    public class Articulo
    {
        [PrimaryKey,AutoIncrement]
        public string Id { get; set; }
        public string Producto { get; set; }
        public int Precio { get; set; }
        public int Cantidad { get; set; }
        public string MasterCategory { get; set; }
        public string Category1 { get; set; }
        public string Category2 { get; set; }
        public string Category3 { get; set; }
    }
}

This is my xalm file:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Saansa"
             x:Class="Saansa.Inventario"
             Title="Inventario">

            <StackLayout BackgroundColor="#f5cda2">
                <Image Margin="0,0,0,0" HeightRequest="10" Source="inventario.png" ></Image>
                <Label Margin="0,0,0,0" Text="Mi Cafe Delicias" FontAttributes="Bold"
                       FontSize="Large" TextColor="#b27b4b" HorizontalTextAlignment="Center" ></Label>
                <Entry x:Name="txtProducto" Placeholder="Código Producto"></Entry>
                <Entry x:Name="txtNombre" Placeholder="Nombre del producto"></Entry>
                <Entry x:Name="txtPrecio" Placeholder="Precio del producto"></Entry>
                <Entry x:Name="txtCantidad" Placeholder="Cantidad del Producto"></Entry>
                <Entry x:Name="txtMainCategory" Placeholder="Categoria general"></Entry>
                <Entry x:Name="txtSub1" Placeholder="Subcategoria 1"></Entry>
                <Entry x:Name="txtSub2" Placeholder="Subcategoria 2"></Entry>
                <Entry x:Name="txtSub3" Placeholder="Subcategoria 3"></Entry>
        <StackLayout  HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
                    <Button x:Name="btnAdd" WidthRequest="200" Text="Añadir" Clicked="BtnAdd_Clicked"
                            BackgroundColor="White" BorderColor="#b27b4b" BorderWidth="3" CornerRadius="15"/>
                    <Button x:Name="btnRead" WidthRequest="200" Text="Buscar" Clicked="BtnRead_Clicked"
                            BackgroundColor="White" BorderColor="#b27b4b" BorderWidth="3" CornerRadius="15"/>
                </StackLayout>
                <StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
                    <Button x:Name="btnUpdate" WidthRequest="200" Text="Actualizar" Clicked="BtnUpdate_Clicked"
                            BackgroundColor="White" BorderColor="#b27b4b" BorderWidth="3" CornerRadius="15"/>
                    <Button x:Name="btnDelete" WidthRequest="200" Text="Borrar" Clicked="BtnDelete_Clicked"
                            BackgroundColor="White" BorderColor="#b27b4b" BorderWidth="3" CornerRadius="15"/>
                </StackLayout>
                <ListView x:Name="lstArticulo" BackgroundColor="#f5cda2">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <StackLayout>
                                    <Label Text="{Binding Producto}"/>
                                    <Label Text="{Binding Id}" HorizontalOptions="EndAndExpand"
                                           TextColor="Black"/>
                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackLayout>
</ContentPage>

In my Inventario.xalm.cs my update option is this:

 private async void BtnUpdate_Clicked(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtProducto.Text))
            {
                Modelos.Articulo articulo = new Modelos.Articulo()
                {
                    Id = txtProducto.Text,
                    Producto = txtNombre.Text,
                    Precio = Convert.ToInt32(txtPrecio.Text),
                    Cantidad = Convert.ToInt32(txtCantidad.Text),
                    MasterCategory = txtMainCategory.Text,
                    Category1 = txtSub1.Text,
                    Category2 = txtSub2.Text,
                    Category3 = txtSub3.Text
                };

                //Update Person
                await App.SQLiteDb.SaveItemAsync(articulo);

                txtNombre.Text = string.Empty;
                txtCantidad.Text = string.Empty;
                txtProducto.Text = string.Empty;
                txtPrecio.Text = string.Empty;
                txtMainCategory.Text = string.Empty;
                txtSub1.Text = string.Empty;
                txtSub2.Text = string.Empty;
                txtSub3.Text = string.Empty;
                await DisplayAlert("Success", "Person Updated Successfully", "OK");
                //Get All Persons
                var articuloLista = await App.SQLiteDb.GetItemsAsync();
                if (articuloLista != null)
                {
                    lstArticulo.ItemsSource = articuloLista;
                }

            }
            else
            {
                await DisplayAlert("Required", "Please Enter Nombre articulo", "OK");
            }
        }


and my SQLiteHekper.cs:

public Task<int> SaveItemAsync(Modelos.Articulo articulo)
        {   //articulo.Cantidad. !string.IsNullOrEmpty(articulo.Cantidad)
            if (!string.IsNullOrEmpty(articulo.Id))
            {
                //probando esto 
                //var nuevoArticulo = GetItemAsync(articulo.Producto);
                return db.UpdateAsync(articulo);
            }  
            else
            {
                return db.InsertAsync(articulo);
            }
        }

The error is that it was not getting the object, thats why first we need to call it and then edit the Articulo that we want to update.

Private async void BtnUpdate_Clicked(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(txtNombre.Text))
        {
            Modelos.Articulo articulo = await App.SQLiteDb.GetItemAsync(txtNombre.Text);

            //Aparentemente dejar el texto vacío no es equivalente a "", por eso el +"0"
            articulo.Cantidad = (string.Equals("0", txtCantidad.Text + "0")) ? articulo.Cantidad : Convert.ToInt32(txtCantidad.Text);
            articulo.Category1 = (string.Equals("0", txtSub1.Text + "0")) ? articulo.Category1 : txtSub1.Text;
            articulo.Category2 = (string.Equals("0", txtSub2.Text + "0")) ? articulo.Category2 : txtSub2.Text;
            articulo.Category3 = (string.Equals("0", txtSub3.Text + "0")) ? articulo.Category3 : txtSub3.Text;
            articulo.MasterCategory = (string.Equals("0", txtMainCategory.Text + "0")) ? articulo.MasterCategory : txtMainCategory.Text;
            articulo.Precio = (string.Equals("0", txtPrecio.Text + "0")) ? articulo.Precio : Convert.ToInt32(txtPrecio.Text);
            articulo.Costo = (String.Equals("0", txtCosto.Text + "0")) ? articulo.Costo : Convert.ToInt32(txtCosto.Text);
            articulo.Producto = (string.Equals("0", txtProducto.Text + "0")) ? articulo.Producto : txtNombre.Text;

            await App.SQLiteDb.SaveItemAsync(articulo);

            txtNombre.Text = string.Empty;
            txtCantidad.Text = string.Empty;
            txtProducto.Text = string.Empty;
            txtCosto.Text = string.Empty;
            txtPrecio.Text = string.Empty;
            txtMainCategory.Text = string.Empty;
            txtSub1.Text = string.Empty;
            txtSub2.Text = string.Empty;
            txtSub3.Text = string.Empty;
            await DisplayAlert("Success", "Producto actualizado con éxito", "OK");


        }
        else
        {
            await DisplayAlert("Required", "Please Enter código articulo", "OK");
        }
    }

This makes to bring the object first, check if some data is not in the entry to let it be like it is and finally it updates the object.

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