Format a Decimal Type Field and Inlcuir in Xamarin Sqlite Forms with Android

Asked

Viewed 220 times

1

Hello to the Masters of Xamarin Forms, I have a little problem, for you maybe very simple. I am not able to format a decimal type field in monetary value and then do the same Insert in Sqlite. Below the code of the Class Products.Cs:

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

namespace rei_das_verduras.Model
{
    public class Produtos
    {
        [PrimaryKey, AutoIncrement]
        public long? pro_id { get; set; }
        public string pro_nome { get; set; }
        public decimal pro_preco_unitario { get; set; }
    }
}

Below the code of the Product Classdal.Cs:

using rei_das_verduras.Infra;
using rei_das_verduras.Model;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;

namespace rei_das_verduras.DAL
{
    public class ProdutosDAL
    {
        private SQLiteConnection sqlConnection;

        public ProdutosDAL()
        {
            this.sqlConnection = DependencyService.Get<ISQLiteDBConnection>().DbConnection();
            this.sqlConnection.CreateTable<Produtos>();
        }

        public void Add(Produtos produto)
        {
            sqlConnection.Insert(produto);
        }

        public void DeleteById(long id)
        {
            sqlConnection.Delete<Produtos>(id);
        }

        public void Update(Produtos produto)
        {
            sqlConnection.Update(produto);
        }

        public IEnumerable<Produtos> GetAll()
        {
            return (from t in sqlConnection.Table<Produtos>() select t).OrderBy(i => i.pro_nome).ToList();
        }

        public Produtos GetProdutoById(long id)
        {
            return sqlConnection.Table<Produtos>().FirstOrDefault(t => t.pro_id == id);
        }
    }
}

Below code of the Class Products:

using MvvmHelpers;
using rei_das_verduras.DAL;
using rei_das_verduras.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;

namespace rei_das_verduras.ViewModel
{
    public class ProdutosViewModel : BaseViewModel
    {
        ProdutosDAL produtoDAL = new ProdutosDAL();

        private ObservableCollection<Produtos> _produtos;
        public ObservableCollection<Produtos> Produtos
        {
            get { return _produtos; }
            set
            {
                if (_produtos != value)
                {
                    _produtos = value;
                    OnPropertyChanged(nameof(Produtos));
                }
            }
        }

        private long? _pro_id;
        private string _pro_nome;
        private decimal _pro_preco_unitario;

        public ProdutosViewModel()
        {
            Produtos = new ObservableCollection<Produtos>(produtoDAL.GetAll());
        }

        public ProdutosViewModel(Produtos produto)
        {
            this._pro_id = produto.pro_id;
            this._pro_nome = produto.pro_nome;
            this._pro_preco_unitario = produto.pro_preco_unitario;
            Produtos = new ObservableCollection<Produtos>(produtoDAL.GetAll());
        }

        public long? pro_id
        {
            get { return _pro_id; }
            set { _pro_id = value; OnPropertyChanged(); }
        }

        public string pro_nome
        {
            get { return _pro_nome; }
            set { _pro_nome = value; OnPropertyChanged(); }
        }

        public decimal pro_preco_unitario
        {
            get { return _pro_preco_unitario; }
            set { _pro_preco_unitario = value; OnPropertyChanged(); }
        }

        public void RemoverProduto(Produtos pro)
        {
            try
            {
                produtoDAL.DeleteById((long)pro.pro_id);
            }
            catch
            {
                App.Current.MainPage.DisplayAlert("Erro na Exclusão", "Falha ao Excluir Produto !!!!", "OK");
            }
        }

        public ICommand Gravar
        {
            get
            {
                var produtoDAL = new ProdutosDAL();
                return new Command(() =>
                {

                    Produtos pro = GetProduto();
                    if ((pro.pro_nome != null) && (pro.pro_preco_unitario != 0))
                    {

                        produtoDAL.Add(pro);
                        App.Current.MainPage.DisplayAlert("Novo Produto", "Produto Incluído com Sucesso !!!!", "OK");
                    }
                    else
                    {
                        App.Current.MainPage.DisplayAlert("Erro na Inclusão", "Produto não Foi Incluído !!!!", "OK");
                    }
                });
            }
        }

        public ICommand Alterar
        {
            get
            {
                var produtoDAL = new ProdutosDAL();
                return new Command(() =>
                {
                    Produtos pro = GetProduto();
                    if ((pro.pro_nome != null) && (pro.pro_preco_unitario != 0))
                    {
                        produtoDAL.Update(pro);
                        App.Current.MainPage.DisplayAlert("Alterar Produto", "Alteração do Produto Realizada com Sucesso !!!!", "OK");
                    }
                    else
                    {
                        App.Current.MainPage.DisplayAlert("Erro na Alteraçpão", "Produto não Foi Alterado !!!!", "OK");
                    }
                });
            }
        }

        private Produtos GetProduto()
        {
            return new Produtos()
            {
                pro_id = this.pro_id,
                pro_nome = this.pro_nome,
                pro_preco_unitario = this.pro_preco_unitario
            };
        }
    }
}

Below the code of Telaprodutos.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="rei_das_verduras.Views.TelaProdutos"
             BackgroundImage="fundo_telas.jpg"
             Title="Produtos">
    <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <ListView x:Name="lvProdutos" HasUnevenRows="True" SeparatorColor="Blue"
                HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.ContextActions>
                            <MenuItem Clicked="OnAlterarClick" CommandParameter="{Binding .}" Text="Alterar"/>
                            <MenuItem Clicked="OnRemoverClick" CommandParameter="{Binding .}" Text="Excluir" IsDestructive="True"/>
                        </ViewCell.ContextActions>
                        <StackLayout Orientation="Horizontal" Padding="2">
                            <StackLayout HorizontalOptions="StartAndExpand">
                                <Label Text="{Binding pro_nome}" TextColor="Blue" FontSize="Medium"/>
                                <Label Text="{Binding pro_preco_unitario, StringFormat=' {0}'}" TextColor="Black" FontSize="Medium"/>
                            </StackLayout>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <StackLayout Padding="0" VerticalOptions="End">
            <Button Text="Incluir Produto" x:Name="BtnNovoItem" Image="novo.jpg" BackgroundColor="White"/>
        </StackLayout>
    </StackLayout>
</ContentPage>

Below the code of Telaprodutos.xaml.Cs:

using rei_das_verduras.Model;
using rei_das_verduras.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace rei_das_verduras.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TelaProdutos : ContentPage
    {
        private ProdutosViewModel produtos;
        private ObservableCollection<Produtos> _produtos;

        public TelaProdutos ()
        {
            InitializeComponent ();
            BtnNovoItem.Clicked += BtnNovoItemClick;
        }
        protected override void OnAppearing()
        {
            base.OnAppearing();
            produtos = new ProdutosViewModel();
            _produtos = produtos.Produtos;
            lvProdutos.ItemsSource = produtos.Produtos;
        }

        private async void BtnNovoItemClick(object sender, EventArgs e)
        {
            Produtos produto = new Produtos();
            await Navigation.PushAsync(new TelaProdutosCRUD(produto));
        }

        private async void OnAlterarClick(object sender, EventArgs e)
        {
            try
            {
                var mi = ((MenuItem)sender);
                var produto = mi.CommandParameter as Produtos;
                if (produto != null)
                {
                    await Navigation.PushAsync(new TelaProdutosCRUD(produto));
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Erro : ", ex.Message, "OK");
            }
        }

        private async void OnRemoverClick(object sender, EventArgs e)
        {
            var mi = ((MenuItem)sender);
            var produto = mi.CommandParameter as Produtos;
            if (produto != null)
            {
                var opcao = await DisplayAlert("Excluir Produto", "Deseja Realmente Excluir Este Produto ? :    " + produto.pro_nome.ToUpper() + " ? ", "Sim", "Não");
                if (opcao)
                {
                    var produtos = new ProdutosViewModel();
                    produtos.RemoverProduto(produto);
                    _produtos.Remove(produto);
                }
            }
            else
            {
                await DisplayAlert("Erro na Exclusão", "Não Foi Possível Excluir o Produto !!!!", "OK");
            }
        }
    }
}

Below the code of Telaprodutoscrud.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="rei_das_verduras.Views.TelaProdutosCRUD"
             BackgroundImage="fundo_telas.jpg"
             Title="Produtos">
    <StackLayout VerticalOptions="Center" Padding="6">
        <StackLayout>
            <Entry  Placeholder="Nome do Produto" x:Name="txtpro_nome" Text="{Binding pro_nome}"/>
            <Entry  Placeholder="Preço Unitário" x:Name="txtpro_preco_unitario" Text="{Binding pro_preco_unitario, StringFormat=' {0}'}" Keyboard="Numeric"/>
        </StackLayout>
        <StackLayout Orientation="Horizontal" HorizontalOptions="Center">
            <Button Text="Incluir Produto" x:Name="btnIncluirPro" Command="{Binding Gravar}" HorizontalOptions="Center"/>
            <Button Text="Alterar Produto" x:Name="btnAlterarPro" Command="{Binding Alterar}" HorizontalOptions="Center"/>
        </StackLayout>
    </StackLayout>
</ContentPage>

Below the code of Telaprodutoscrud.xaml.Cs:

using rei_das_verduras.Model;
using rei_das_verduras.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace rei_das_verduras.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TelaProdutosCRUD : ContentPage
    {
        private string titulo;

        public TelaProdutosCRUD (Produtos produto)
        {
            InitializeComponent ();
            if (produto.pro_id == null)
            {
                Title = "Incluir Novo Produto";
                titulo = "Inclusão";
                btnAlterarPro.IsVisible = false;
            }
            else
            {
                Title = "Alterar Dados do Produto";
                titulo = "Alteração de dados";
                btnIncluirPro.IsVisible = false;
            }

            var produtovm = new ProdutosViewModel(produto);
            BindingContext = produtovm;
        }
    }
}

What I want is to format the field of the decimal type pro_preco_unitario, so that it can be written in the following format R$ 5,36 or larger value in currency. Waiting for the masters, if possible. I thank you in advance for the help.

  • I don’t think it’s a good idea literally write to the bank the value in the format "R$ 5.36"... Your problem is display and not how to store in the bank. The field should be decimal even, that’s how you will want to use it.

  • On the display, you have basically two options: 1) puts the currency indicator ("R$") in another field Label next to the Entry/Label or 2) controls everything in the same field by adjusting its display to each keystroke (you will need to handle to extract the value as well). This second one I think is better. If it works for you, let me know that I will try to implement an example and you apply it to your real scenario

  • Dear Master Diego Rafael, I would like an example of the 2nd option. Waiting for your contact.

  • Hello, if possible, I am waiting for the example of the 2nd Option, I am very grateful for the help.

  • Sorry, I forgot to show you an example. I will implement tonight and post.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.