Save Date Field to Sqlite and view Date using Datepicker

Asked

Viewed 289 times

-1

Hello to the master of Xamarin.Forms Android, I’m trying to record a date in Sqlite, using xzamarin.Forms Android, with a Datepicker, in visual studio 2017, the user must enter the date in the format 11/11/1900 and then record in Sqlite in the american format yy-mm-dd and show to your swas in 11/11/1900 format, as I do, I’m breaking my head with this, I really appreciate anyone who can help. I have in the Model folder, the Sales.Cs class, with the following code:

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

namespace rei_das_verduras.Model
{
    public class Vendas
    {
        [PrimaryKey, AutoIncrement]
        public long? ven_id { get; set; }
        public DateTime ven_data { get; set; }
        public long des_id { get; set; }

        public string DataVenda
        {
            get
            {
                return string.Format("{0:yy-MM-dd}", ven_data);
            }
        }

        public override string ToString()
        {
            return string.Format("{0}", DataVenda);
        }
    }
}

In the DAL folder, I have the Vendasdal.Cs class, with the following code:

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 VendasDAL
    {
        private SQLiteConnection sqlConnection;

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

        public void Add(Vendas vendas)
        {
            sqlConnection.Insert(vendas);
        }

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

        public void Update(Vendas vendas)
        {
            sqlConnection.Update(vendas);
        }

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

        public Vendas GetVendasById(long id)
        {
            return sqlConnection.Table<Vendas>().FirstOrDefault(t => t.ven_id == id);
        }
    }
}

In the Infra folder, I have the Isqlitedbconnection.Cs class, with the following code:

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

namespace rei_das_verduras.Infra
{
    public interface ISQLiteDBConnection
    {
        SQLiteConnection DbConnection();
    }
}

In the Viewmodel folder, I have the Vendasviewmodel.Cs class, with the following code:

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
{
    class VendasViewModel : BaseViewModel
    {
        VendasDAL vendaDAL = new VendasDAL();

        private ObservableCollection<Vendas> _venda;

        public ObservableCollection<Vendas> Venda
        {
            get { return _venda; }
            set
            {
                if (_venda != value)
                {
                    _venda = value;
                    OnPropertyChanged(nameof(Vendas));
                }
            }
        }

        private long? _ven_id;
        private DateTime _ven_data;
        private long _des_id;

        public VendasViewModel()
        {
            Venda = new ObservableCollection<Vendas>(vendaDAL.GetAll());
        }

        public VendasViewModel(Vendas venda)
        {
            this._ven_id = venda.ven_id;
            this._ven_data = venda.ven_data;
            this._des_id = venda.des_id;
            Venda = new ObservableCollection<Vendas>(vendaDAL.GetAll());
        }

        public long? ven_id
        {
            get { return _ven_id; }
            set { _ven_id = value; OnPropertyChanged(); }
        }

        public DateTime ven_data
        {
            get { return _ven_data; }
            set { _ven_data = value; OnPropertyChanged(); }
        }

        public long des_id
        {
            get { return _des_id; }
            set { _des_id = value; OnPropertyChanged(); }
        }

        public void RemoverVenda(Vendas ven)
        {
            try
            {
                vendaDAL.DeleteById((long)ven.ven_id);
            }
            catch
            {
                App.Current.MainPage.DisplayAlert("Erro na Exclusão", "Falha ao Excluir Venda !!!!", "OK");
            }
        }

        public ICommand Gravar
        {
            get
            {
                var vendaDAL = new VendasDAL();
                return new Command(() =>
                {

                    Vendas ven = GetVenda();
                    if ((ven.ven_data != null) && (ven.des_id != 0))
                    {

                        vendaDAL.Add(ven);
                        App.Current.MainPage.DisplayAlert("Nova Venda", "Venda Incluída com Sucesso !!!!", "OK");
                    }
                    else
                    {
                        App.Current.MainPage.DisplayAlert("Erro na Inclusão", "Venda não Foi Incluída !!!!", "OK");
                    }
                });
            }
        }

        public ICommand Alterar
        {
            get
            {
                var vendaDAL = new VendasDAL();
                return new Command(() =>
                {
                    Vendas ven = GetVenda();
                    if ((ven.ven_data != null) && (ven.des_id != 0))
                    {
                        vendaDAL.Update(ven);
                        App.Current.MainPage.DisplayAlert("Alterar Venda", "Alteração da Venda Realizada com Sucesso !!!!", "OK");
                    }
                    else
                    {
                        App.Current.MainPage.DisplayAlert("Erro na Venda", "Venda não Foi Alterada !!!!", "OK");
                    }
                });
            }
        }

        private Vendas GetVenda()
        {
            return new Vendas()
            {
                ven_id = this.ven_id,
                ven_data = this.ven_data,
                des_id = this.des_id,
            };
        }
    }
}

In the View folder, I have the view Telamenu.xaml, with the following code:

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:pag="clr-namespace:rei_das_verduras.Views"
             x:Class="rei_das_verduras.Views.TelaMenu">
    <MasterDetailPage.Master>
        <ContentPage Title="Menu" Padding="0">
            <ContentPage.Content>
                <StackLayout>
                    <Grid>
                        <Image Source="logo.png" Aspect="Fill" />
                    </Grid>
                    <TableView Intent="Menu">
                        <TableSection>
                            <ViewCell Tapped="IrTelaVendas">
                                <StackLayout VerticalOptions="FillAndExpand" Orientation="Horizontal" Padding="20,10,0,10" Spacing="20">
                                    <Image Source="icon_vendas.png" WidthRequest="30" HeightRequest="30" VerticalOptions="Center" />
                                    <Label Text="Tela Vendas" FontSize="Medium" VerticalOptions="Center" TextColor="Black"/>
                                </StackLayout>
                            </ViewCell>
                        </TableSection>
                    </TableView>
                </StackLayout>
            </ContentPage.Content>
        </ContentPage>
    </MasterDetailPage.Master>
</MasterDetailPage>

In the View folder, I have the view Telamenu.xaml.Cs, with the following code:

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 TelaMenu : MasterDetailPage
    {
        public TelaMenu()
        {
            InitializeComponent();
            Detail = new NavigationPage(new TelaPrincipal());
        }


        private void IrTelaVendas(object sender, EventArgs e)
        {
            Detail.Navigation.PushAsync(new TelaVendas());
            IsPresented = false;
        }
    }
}

In the View folder, I have the view Telaprincipal.xaml, with the following code:

<?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.TelaPrincipal"
             BackgroundImage="fundo.jpg"
             Title="Tela Principal">
    <ContentPage.Content>
        <StackLayout Padding="0" VerticalOptions="Start">
            <TableView>
                <TableSection>
                    <ViewCell Tapped="IrTelaVendas">
                        <StackLayout VerticalOptions="FillAndExpand" Orientation="Horizontal" Padding="20,10,0,10" Spacing="20">
                            <Image Source="icon_vendas.png" WidthRequest="30" HeightRequest="30" VerticalOptions="Center" />
                            <Label Text="Tela Vendas" FontSize="Large" Style="bold" VerticalOptions="Center" TextColor="Red"/>
                        </StackLayout>
                    </ViewCell>
                </TableSection>
            </TableView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

In the View folder, I have the view Telaprincipal.xaml.Cs, with the following code:

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 TelaPrincipal : ContentPage
    {
        public TelaPrincipal()
        {
            InitializeComponent();
        }

        private void IrTelaVendas(object sender, EventArgs e)
        {
            Navigation.PushAsync(new TelaVendas());
        }
    }
}

In the View folder, I have the view Telavendas.xaml, with the following code:

<?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.TelaVendas"
             BackgroundImage="fundo_telas.jpg"
             Title="Vendas">
    <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <ListView x:Name="lvVendas" 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 ven_data}" TextColor="Blue" FontSize="Medium"/>
                                <Label Text="{Binding des_id}" TextColor="Black" FontSize="Medium"/>
                            </StackLayout>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <StackLayout Padding="0" VerticalOptions="End">
            <Button Text="Incluir Venda" x:Name="BtnNovaVenda" Image="novo.jpg" BackgroundColor="White"/>
        </StackLayout>
    </StackLayout>
</ContentPage>

In the View folder, I have the view Telavendas.xaml.Cs, with the following code:

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 TelaVendas : ContentPage
    {
        private VendasViewModel vendas;
        private ObservableCollection<Vendas> _vendas;

        public TelaVendas()
        {
            InitializeComponent();
            BtnNovaVenda.Clicked += BtnNovaVendaClick;
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            vendas = new VendasViewModel();
            _vendas = vendas.Venda;
            lvVendas.ItemsSource = vendas.Venda;
        }

        private async void BtnNovaVendaClick(object sender, EventArgs e)
        {
            Vendas venda = new Vendas();
            await Navigation.PushAsync(new TelaVendasCRUD(venda));
        }

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

        private async void OnRemoverClick(object sender, EventArgs e)
        {
            var mi = ((MenuItem)sender);
            var venda = mi.CommandParameter as Vendas;
            if (venda != null)
            {
                var opcao = await DisplayAlert("Excluir Venda", "Deseja Realmente Excluir Esta Venda ? :    " + venda.ven_id + " ? ", "Sim", "Não");
                if (opcao)
                {
                    var vendas = new VendasViewModel();
                    vendas.RemoverVenda(venda);
                    _vendas.Remove(venda);
                }
            }
            else
            {
                await DisplayAlert("Erro na Exclusão", "Não Foi Possível Excluir a Venda !!!!", "OK");
            }
        }
    }
}

In the View folder, I have the view Telavendascrud.xaml, with the following code:

<?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.TelaVendasCRUD"
             BackgroundImage="fundo_telas.jpg"
             Title="Vendas">
    <StackLayout VerticalOptions="Center" Padding="6">
        <StackLayout>
            <Label Text="Data da Venda" />
            <DatePicker x:Name="txtven_data" Date="{Binding ven_data}" Format="dd/MM/yyyy" />
            <Entry  Placeholder="Código Destino Exportação" x:Name="txtdes_id" Text="{Binding des_id}" Keyboard="Numeric"/>
        </StackLayout>
        <StackLayout Orientation="Horizontal" HorizontalOptions="Center">
            <Button Text="Incluir Venda" x:Name="btnIncluirVenda" Command="{Binding Gravar}" HorizontalOptions="Center"/>
            <Button Text="Alterar Venda" x:Name="btnAlterarVenda" Command="{Binding Alterar}" HorizontalOptions="Center"/>
        </StackLayout>
    </StackLayout>
</ContentPage>

In the View folder, I have the view Telavendascrud.xaml.Cs, with the following code:

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 TelaVendasCRUD : ContentPage
    {
        private string titulo;

        public TelaVendasCRUD(Vendas venda)
        {
            InitializeComponent();
            if (venda.ven_id == null)
            {
                Title = "Incluir Nova Venda";
                titulo = "Inclusão";
                btnAlterarVenda.IsVisible = false;
            }
            else
            {
                Title = "Alterar Dados da Venda";
                titulo = "Alteração de dados";
                btnIncluirVenda.IsVisible = false;
            }

            var vendavm = new VendasViewModel(venda);
            BindingContext = vendavm;
        }
    }
}

I have the view App.xaml.Cs, with the following code:

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

[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
namespace rei_das_verduras
{
    public partial class App : Application
    {
        public App ()
        {
            InitializeComponent();

            MainPage = new rei_das_verduras.Views.TelaMenu();
        }

        protected override void OnStart ()
        {
            // Handle when your app starts
        }

        protected override void OnSleep ()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume ()
        {
            // Handle when your app resumes
        }
    }
}

In the Android project, I have in the folder Sqlitedbconnection, the Sqlitedbconnection_android.Cs class, with the following code:

using rei_das_verduras.Droid.SQLiteDBConnection;
using rei_das_verduras.Infra;
using SQLite;
using SQLite.Net.Platform.XamarinAndroid;
using System.IO;

[assembly: Xamarin.Forms.Dependency(typeof(SQLiteDBConnection_Android))]
namespace rei_das_verduras.Droid.SQLiteDBConnection
{
    public class SQLiteDBConnection_Android : ISQLiteDBConnection
    {
        public SQLiteConnection DbConnection()
        {
            var dbName = "rei_das_verduras.db3";
            string documentsFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string path = Path.Combine(documentsFolder, dbName);
            var platform = new SQLitePlatformAndroid();
            return new SQLiteConnection(path);
        }
    }
}

Well that’s it, I know that for the masters, this is a basic problem, for me, that I’m trying to learn goes beyond imagination. Anyone who can help, thank you in advance. I’m using MVVM and the sqlite-net-Pcl 1.4.118 and Refractored.Mvvmhelpers 1.3.0 plugin.

1 answer

0

Great masters, my code has no errors, I just forgot to implode in the visualization template the code: , Stringformat='{0:dd/MM/yyyy}', in the label field Bading. Most grateful.

Browser other questions tagged

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