0% found this document useful (0 votes)
10 views16 pages

Xamarin

Uploaded by

tacankent315
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views16 pages

Xamarin

Uploaded by

tacankent315
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

MAIN.

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="ElectNext.MainPage">

<StackLayout>
<StackLayout>
<StackLayout HorizontalOptions="Center" VerticalOptions="Start">

<Label Margin="0,0,0,10" Text="JAY CEBECO 101" FontAttributes="Bold"


FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>
<Entry x:Name="txtMeterNum" Placeholder="MeterNum - Update and
Delete"></Entry>
<Entry x:Name="txtPresent" Placeholder="Input Present Reading"></Entry>
<Entry x:Name="txtPrevious" Placeholder="Input Previous Reading"></Entry>

<StackLayout Orientation="Horizontal" Margin="0,10,10,0">

<CheckBox x:Name="chkH" Margin="5,0,0,0" />


<Label Text="H" VerticalOptions="Center" FontAttributes="Bold"
FontSize="Large" TextColor="Black"/>
</StackLayout>

<StackLayout Orientation="Horizontal" Margin="0,10,10,0">

<CheckBox x:Name="chkB" Margin="5,0,0,0" />


<Label Text="B" VerticalOptions="Center" FontAttributes="Bold"
FontSize="Large" TextColor="Black"/>
</StackLayout>

<StackLayout HorizontalOptions="CenterAndExpand"
Orientation="Horizontal">
<Button x:Name="btnAdd" WidthRequest="200" Text="Add"
Clicked="BtnAdd_Clicked" />
<Button x:Name="btnRead" WidthRequest="200" Text="Read"
Clicked="BtnRead_Clicked" />
</StackLayout>

<StackLayout HorizontalOptions="CenterAndExpand"
Orientation="Horizontal">
<Button x:Name="btnUpdate" WidthRequest="200" Text="Update"
Clicked="BtnUpdate_Clicked"/>
<Button x:Name="btnDelete" WidthRequest="200" Text="Delete"
Clicked="BtnDelete_Clicked" />
</StackLayout>

<ListView x:Name="sPersons">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid Padding="5">
<Grid.RowDefinitions>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition Height="10"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition
Width="1*"></ColumnDefinition>
<ColumnDefinition
Width="2*"></ColumnDefinition>
<ColumnDefinition
Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>

<BoxView Color="Navy" HeightRequest="2"


Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3"/>
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

</StackLayout>
</StackLayout>
</StackLayout>

</ContentPage>

MAIN.XAML.CS
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Xamarin.Forms;

namespace ElectNext

public partial class MainPage : ContentPage

private List<Person> personsList = new List<Person>(); // Koleksyon ng Persons


public MainPage()

InitializeComponent();

protected async override void OnAppearing()

base.OnAppearing();

// Load Persons from SQLite database

var personList = await App.SQLiteDb.GetItemsAsync();

if (personList != null)

personsList = personList.ToList(); // Set the loaded list to personsList

sPersons.ItemsSource = personsList; // Set ItemsSource to loaded list

private double demandCharge = 0;

private double serviceCharge = 0;

private double electricityCharge = 0;

private async void BtnAdd_Clicked(object sender, EventArgs e)

try

// Validate input

if (string.IsNullOrEmpty(txtPresent.Text) ||
string.IsNullOrEmpty(txtPrevious.Text) ||

(chkH.IsChecked == false && chkB.IsChecked == false))

await DisplayAlert("Error", "All fields are required.", "OK");

return;

// Parse input

if (!double.TryParse(txtPresent.Text, out double presentReading) ||

!double.TryParse(txtPrevious.Text, out double previousReading))

await DisplayAlert("Error", "Present and Previous readings must be numeric.", "OK");

return;

// Calculate ConsumptionReading

double consumptionReading = presentReading - previousReading;

// Calculate electricityCharge

if (consumptionReading < 72)

electricityCharge = consumptionReading * 6.50;

else if (consumptionReading <= 150)

electricityCharge = consumptionReading * 9.50;


}

else if (consumptionReading <= 300)

electricityCharge = consumptionReading * 10.50;

else if (consumptionReading <= 400)

electricityCharge = consumptionReading * 12.50;

else if (consumptionReading <= 500)

electricityCharge = consumptionReading * 14.00;

else

electricityCharge = consumptionReading * 16.50;

if (chkH.IsChecked)

demandCharge = 300;

serviceCharge = 200;

if (chkB.IsChecked)

demandCharge = 600;

serviceCharge = 400;

}
// Calculate PrincipalAmount

double principalAmount = electricityCharge + demandCharge + serviceCharge;

// Calculate Vat and AmountPayable

double vat = principalAmount * 0.05;

double amountPayable = principalAmount + vat;

// Create Person object

Person person = new Person

PresentReading = presentReading,

PreviousReading = previousReading,

TypeOfRegistration = chkH.IsChecked ? "H" : "B",

ConsumptionReading = consumptionReading,

ElectricityCharge = electricityCharge,

DemandCharge = demandCharge,

ServiceCharge = serviceCharge,

PrincipalAmount = principalAmount,

Vat = vat,

AmountPayable = amountPayable

};

// Add person to the list

personsList.Add(person);
// Save personsList to SQLite database

await App.SQLiteDb.SaveItemsAsync(personsList);

// Update ListView

sPersons.ItemsSource = null; // Clear ItemsSource

sPersons.ItemsSource = personsList; // Set ItemsSource to updated list

// Clear input fields

txtPresent.Text = "";

txtPrevious.Text = "";

chkH.IsChecked = false;

chkB.IsChecked = false;

await Navigation.PushAsync(new newpage());

catch (Exception ex)

await DisplayAlert("Error", $"An error occurred: {ex.Message}", "OK");

private async void BtnRead_Clicked(object sender, EventArgs e)

if (!string.IsNullOrEmpty(txtMeterNum.Text))

// Get Person

var person = await App.SQLiteDb.GetItemAsync(Convert.ToInt32(txtMeterNum.Text));

if (person != null)
{

// Display the MeterNo, PrincipalAmount, and AmountPayable in an alert

string message = $"Meter No: {person.MeterNo}\n" +

$"Principal Amount: {person.PrincipalAmount}\n" +

$"Amount Payable: {person.AmountPayable}";

await DisplayAlert("Success", message, "OK");

txtMeterNum.Text = "";

txtPresent.Text = "";

txtPrevious.Text = "";

else

await DisplayAlert("Not Found", "No person found with the given Meter No.", "OK");

else

await DisplayAlert("Required", "Please enter the Meter No.", "OK");

private async void BtnUpdate_Clicked(object sender, EventArgs e)

try

if (!string.IsNullOrEmpty(txtMeterNum.Text))

{
// Fetch the person from the database using Meter No

var person = await App.SQLiteDb.GetItemAsync(Convert.ToInt32(txtMeterNum.Text));

if (person != null)

// Update the fields

if (!string.IsNullOrEmpty(txtPresent.Text) && double.TryParse(txtPresent.Text, out double


presentReading))

person.PresentReading = presentReading;

else

await DisplayAlert("Error", "Present reading must be a valid number.", "OK");

return;

// Handle checkboxes first to update demandCharge and serviceCharge

if (chkH.IsChecked)

person.DemandCharge = 300;

person.ServiceCharge = 200;

else if (chkB.IsChecked)

person.DemandCharge = 600;

person.ServiceCharge = 400;

else

{
person.DemandCharge = 0;

person.ServiceCharge = 0;

// Calculate ConsumptionReading

double consumptionReading = person.PresentReading - person.PreviousReading;

// Recalculate electricityCharge based on consumptionReading

if (consumptionReading < 72)

person.ElectricityCharge = consumptionReading * 6.50;

else if (consumptionReading <= 150)

person.ElectricityCharge = consumptionReading * 9.50;

else if (consumptionReading <= 300)

person.ElectricityCharge = consumptionReading * 10.50;

else if (consumptionReading <= 400)

person.ElectricityCharge = consumptionReading * 12.50;

else if (consumptionReading <= 500)

person.ElectricityCharge = consumptionReading * 14.00;

else
{

person.ElectricityCharge = consumptionReading * 16.50;

// Calculate PrincipalAmount

person.PrincipalAmount = person.ElectricityCharge + person.DemandCharge +


person.ServiceCharge;

// Calculate Vat and AmountPayable

person.Vat = person.PrincipalAmount * 0.05;

person.AmountPayable = person.PrincipalAmount + person.Vat;

// Save the updated person to the database

await App.SQLiteDb.SaveItemAsync(person);

// Display success message

await DisplayAlert("Success", "Person Updated Successfully", "OK");

txtMeterNum.Text = "";

txtPresent.Text = "";

txtPrevious.Text = "";

else

await DisplayAlert("Error", "Person not found.", "OK");

else

await DisplayAlert("Required", "Please Enter Meter No", "OK");


}

catch (Exception ex)

await DisplayAlert("Error", $"An error occurred: {ex.Message}", "OK");

private async void BtnDelete_Clicked(object sender, EventArgs e)

if (!string.IsNullOrEmpty(txtMeterNum.Text))

// Fetch the person from the database using Meter No

var person = await App.SQLiteDb.GetItemAsync(Convert.ToInt32(txtMeterNum.Text));

if (person != null)

// Delete Person

await App.SQLiteDb.DeleteItemAsync(person);

txtMeterNum.Text = string.Empty;

await DisplayAlert("Success", "Person Deleted", "OK");

// Refresh the list of persons

RefreshPersonsList();

txtMeterNum.Text = "";

else
{

await DisplayAlert("Error", "Person not found.", "OK");

else

await DisplayAlert("Required", "Please Enter Meter No", "OK");

// Method to refresh the list of persons displayed in the ListView

private async void RefreshPersonsList()

// Get all persons from the database

var personList = await App.SQLiteDb.GetItemsAsync();

if (personList != null)

// Update the ItemsSource of the ListView

sPersons.ItemsSource = personList;

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

namespace ElectNext
{
public class Person
{
[PrimaryKey, AutoIncrement]
public int MeterNo { get; set; }
public double PresentReading { get; set; }
public double PreviousReading { get; set; }
public String TypeOfRegistration { get; set; }
public double ConsumptionReading { get; set; }
public double ElectricityCharge { get; set; }
public double DemandCharge { get; set; }
public double ServiceCharge { get; set; }
public double PrincipalAmount { get; set; }
public double Vat { get; set; }
public double AmountPayable { get; set; }

SQLiteHelper.CS

using SQLite;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ElectNext
{
public class SQLiteHelper
{
SQLiteAsyncConnection db;

public SQLiteHelper(string dbPath)


{
db = new SQLiteAsyncConnection(dbPath);
db.CreateTableAsync<Person>().Wait();
}

// Insert and Update new record


public Task<int> SaveItemAsync(Person person)
{
if (person.MeterNo != 0)
{
return db.UpdateAsync(person);
}
else
{
return db.InsertAsync(person);
}
}

// Save a list of items


public async Task SaveItemsAsync(List<Person> persons)
{
foreach (var person in persons)
{
await SaveItemAsync(person);
}
}
// Delete
public Task<int> DeleteItemAsync(Person person)
{
return db.DeleteAsync(person);
}

// Read All Items


public Task<List<Person>> GetItemsAsync()
{
return db.Table<Person>().ToListAsync();
}

// Read Item
public Task<Person> GetItemAsync(int personId)
{
return db.Table<Person>().Where(i => i.MeterNo ==
personId).FirstOrDefaultAsync();
}
}
}

NEWPAGE.XAML.CS
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace ElectNext
{

public partial class newpage : ContentPage


{
private List<Person> personsList = new List<Person>();
public newpage()
{
InitializeComponent();
}
protected async override void OnAppearing()
{
base.OnAppearing();

// Load Persons from SQLite database


var personList = await App.SQLiteDb.GetItemsAsync();
if (personList != null)
{
personsList = personList.ToList(); // Set the loaded list to personsList
sPersons.ItemsSource = personsList; // Set ItemsSource to loaded list
}
}
}
}
NEWPAGE.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="ElectNext.newpage">
<ContentPage.Content>
<ListView x:Name="sPersons">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid Padding="5">
<Grid.RowDefinitions>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition Height="10"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>

<Label Grid.Row="0" Grid.Column="0" Text="{Binding


MeterNo}" HorizontalTextAlignment="Center" VerticalTextAlignment="Center"
TextColor="Black" FontAttributes="Bold"/>
<Label Grid.Row="0" Grid.Column="1" Text="{ Binding
PrincipalAmount }" HorizontalTextAlignment="Center" VerticalTextAlignment="Center"
TextColor="Black"/>
<Label Grid.Row="0" Grid.Column="2" Text="{Binding
AmountPayable}" HorizontalTextAlignment="Center" VerticalTextAlignment="Center"
TextColor="Black" FontAttributes="Bold"/>
<BoxView Color="Navy" HeightRequest="2" Grid.Row="2"
Grid.Column="0" Grid.ColumnSpan="3"/>
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
</ContentPage>

You might also like