How to animate whole frame when clicked on button in xamarin? - c#

I want to fade out whole frame when i click on delete button but i only know how to fade that delete button i have searched I cant find this specific example. In the example below will disapper just delete button and i cant find how to call whole frame to set animation on it.
button:
private async void deleteButton_Clicked(object sender, EventArgs e)
{
var action = await DisplayAlert("Delete", "Do you want delete picture?", "Cancel", "Delete");
if (action)
{
}
else
{
var button = (Button)sender;
button.ScaleTo(1, 1000, Easing.BounceOut);
var plane = (Airplane)button.BindingContext;
var db = new SQLiteConnection(_dbPath);
db.Delete<Airplane>(plane.Id);
Refresh();
}
}
xaml:
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Margin="0">
<Frame Padding="0" BackgroundColor="{AppThemeBinding Light='#00d2ff', Dark='#121212'}" Margin="0, 70, 0, 0" CornerRadius="30">
<StackLayout Padding="20">
<Label Text="{Binding Airline}" TextColor ="White" FontAttributes="Bold" FontSize="35" FontFamily="Lato" Margin="0" HorizontalOptions="Center" HorizontalTextAlignment="Center"/>
<Grid HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Image Source="{Binding ThumbnailUrl}" Aspect="AspectFill"/>
</Grid>
<Label Text="{Binding Plane, StringFormat='Plane: {0}'}" FontFamily="Lato" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Airline, StringFormat='Airline: {0}'}" FontFamily="Lato" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Livery, StringFormat='Livery: {0}'}" FontFamily="Lato" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Registration, StringFormat='Reg: {0}'}" FontFamily="Lato" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Airport, StringFormat='Airport: {0}'}" FontFamily="Lato" TextColor ="White" FontSize="15"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0">
<Label Text="{Binding Date, StringFormat='Date: {0}'}" FontFamily="Lato" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Comment, StringFormat='Comment: {0}'}" FontFamily="Lato" TextColor ="White" FontSize="15"/>
</StackLayout>
<AbsoluteLayout Grid.Column="1">
<Button Text="Delete" TextColor="White" CornerRadius="30" FontAttributes="Bold" FontSize="14" FontFamily="Lato" BackgroundColor="{AppThemeBinding Light='#00aeef', Dark='Black'}" x:Name="deleteButton" Clicked="deleteButton_Clicked" AbsoluteLayout.LayoutBounds="0.8, 0.5, 100, 50" AbsoluteLayout.LayoutFlags="PositionProportional"/>
</AbsoluteLayout>
</Grid>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>

You could try the code below to fade the frame.
In the button click event, we use the parent of button to find the frame.
var frame = button.Parent.Parent.Parent.Parent as Frame;
The whole code:
Xaml:
<CollectionView ItemsSource="{Binding airs}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Margin="0">
<Frame
Margin="0,70,0,0"
Padding="0"
BackgroundColor="{AppThemeBinding Light='#00d2ff',
Dark='#121212'}"
CornerRadius="30">
<StackLayout Padding="20">
<Label
Margin="0"
FontAttributes="Bold"
FontFamily="Lato"
FontSize="35"
HorizontalOptions="Center"
HorizontalTextAlignment="Center"
Text="{Binding Airline}"
TextColor="White" />
<Grid HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Image Aspect="AspectFill" Source="{Binding ThumbnailUrl}" />
</Grid>
<Label
FontFamily="Lato"
FontSize="15"
Text="{Binding Plane, StringFormat='Plane: {0}'}"
TextColor="White" />
<Label
FontFamily="Lato"
FontSize="15"
Text="{Binding Airline, StringFormat='Airline: {0}'}"
TextColor="White" />
<Label
FontFamily="Lato"
FontSize="15"
Text="{Binding Livery, StringFormat='Livery: {0}'}"
TextColor="White" />
<Label
FontFamily="Lato"
FontSize="15"
Text="{Binding Registration, StringFormat='Reg: {0}'}"
TextColor="White" />
<Label
FontFamily="Lato"
FontSize="15"
Text="{Binding Airport, StringFormat='Airport: {0}'}"
TextColor="White" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0">
<Label
FontFamily="Lato"
FontSize="15"
Text="{Binding Date, StringFormat='Date: {0}'}"
TextColor="White" />
<Label
FontFamily="Lato"
FontSize="15"
Text="{Binding Comment, StringFormat='Comment: {0}'}"
TextColor="White" />
</StackLayout>
<AbsoluteLayout Grid.Column="1">
<Button
x:Name="deleteButton"
AbsoluteLayout.LayoutBounds="0.8, 0.5, 100, 50"
AbsoluteLayout.LayoutFlags="PositionProportional"
BackgroundColor="{AppThemeBinding Light='#00aeef',
Dark='Black'}"
Clicked="deleteButton_Clicked"
CornerRadius="30"
FontAttributes="Bold"
FontFamily="Lato"
FontSize="14"
Text="Delete"
TextColor="White" />
</AbsoluteLayout>
</Grid>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Code behind:
public partial class Page1 : ContentPage
{
public ObservableCollection<Air> airs { get; set; }
public Page1()
{
InitializeComponent();
airs = new ObservableCollection<Air>()
{
new Air{ Airline="Airline1", Comment="Comment1", Airport="Airport1", Date="Date1", Livery="Livery1", Plane="Plane1", Registration="Registration1", ThumbnailUrl="pink.jpg"},
new Air{ Airline="Airline2", Comment="Comment2", Airport="Airport2", Date="Date2", Livery="Livery2", Plane="Plane2", Registration="Registration2", ThumbnailUrl="pink.jpg"},
new Air{ Airline="Airline3", Comment="Comment3", Airport="Airport3", Date="Date3", Livery="Livery3", Plane="Plane3", Registration="Registration3", ThumbnailUrl="pink.jpg"},
new Air{ Airline="Airline4", Comment="Comment4", Airport="Airport4", Date="Date4", Livery="Livery4", Plane="Plane4", Registration="Registration4", ThumbnailUrl="pink.jpg"},
new Air{ Airline="Airline5", Comment="Comment5", Airport="Airport5", Date="Date5", Livery="Livery5", Plane="Plane5", Registration="Registration5", ThumbnailUrl="pink.jpg"},
new Air{ Airline="Airline6", Comment="Comment6", Airport="Airport6", Date="Date6", Livery="Livery6", Plane="Plane6", Registration="Registration6", ThumbnailUrl="pink.jpg"},
};
this.BindingContext = this;
}
private void deleteButton_Clicked(object sender, EventArgs e)
{
var button = sender as Button;
var frame = button.Parent.Parent.Parent.Parent as Frame;
frame.FadeTo(0.5);
}
}
public class Air
{
public string Airline { get; set; }
public string Plane { get; set; }
public string ThumbnailUrl { get; set; }
public string Livery { get; set; }
public string Registration { get; set; }
public string Airport { get; set; }
public string Date { get; set; }
public string Comment { get; set; }
}
Screenshot:

Step 1 :
Give a x:Name to your Frame
<Frame x:Name="AnimationFrame" Padding="0" BackgroundColor="{AppThemeBinding Light='#00d2ff', Dark='#121212'}" Margin="0, 70, 0, 0" CornerRadius="30">
Step 2 : Pass this frame in Button's CommandParameter
<Button Text="Delete" TextColor="White" CornerRadius="30" FontAttributes="Bold" FontSize="14" FontFamily="Lato" BackgroundColor="{AppThemeBinding Light='#00aeef', Dark='Black'}" x:Name="deleteButton" Clicked="deleteButton_Clicked" AbsoluteLayout.LayoutBounds="0.8, 0.5, 100, 50" AbsoluteLayout.LayoutFlags="PositionProportional"
CommandParameter="{x:Reference AnimationFrame}"/>
Step 3: Recieve this frame in CodeBehind
private async void deleteButton_Clicked(object sender, EventArgs e)
{
if (sender is Xamarin.Forms.Button button && button.CommandParameter is Xamarin.Forms.Frame frame)
{
// You now have the frame element
// write your animation logic to the entire frame now
frame.FadeTo(0.5);
}
}

Related

How to set SelectedColour Property for TabView using TabViewItemDataTemplate?

I am working on TabView control to create multiple tab page using "TabItemSource". In most of the sample provided in open source, the "TextColorSelected" property can be set in xct:TabViewItem. For my case, how can I set "TextColorSelected" property while using TabItemSource?
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:xct="clr-namespace:Xamarin.CommunityToolkit.UI.Views;assembly=Xamarin.CommunityToolkit"
x:Class="MultiPosApp.Restaurant.Views.KitchenOrderTicketView"
xmlns:prism="http://prismlibrary.com"
prism:ViewModelLocator.AutowireViewModel="True"
x:Name="KitchenOrderTicketVM"
Title="Kitchen Order Ticket">
<xct:TabView TabItemsSource="{Binding KitchenOrderCollection}" TabStripPlacement="Top" TabStripBackgroundColor="AliceBlue" TabStripHeight="50" IsSwipeEnabled="False" TabIndicatorColor="Black"
AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All" SelectedIndex="{Binding SelectedIdx}">
<xct:TabView.TabViewItemDataTemplate>
<DataTemplate>
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand">
<Label Text="{Binding Location}"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
TextColor="Black"
FontAttributes="Bold"/>
</StackLayout>
</DataTemplate>
</xct:TabView.TabViewItemDataTemplate>
<xct:TabView.TabContentDataTemplate>
<DataTemplate>
<ScrollView>
<StackLayout BindableLayout.ItemsSource="{Binding TableOrderCollection}" Orientation="Vertical" Margin="3">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Frame BorderColor="LightGray" Padding="10" BackgroundColor="GhostWhite" HasShadow="True" CornerRadius="10">
<StackLayout Orientation="Vertical">
<StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand">
<Label Text="TABLE " TextColor="Black" FontSize="Large" FontAttributes="Bold"/>
<Label Text="{Binding Table.TableNum}" TextColor="Black" FontSize="Large" FontAttributes="Bold"/>
</StackLayout>
<StackLayout BindableLayout.ItemsSource="{Binding MenuOrderCollection}" Orientation="Vertical">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Label Text="{Binding ItemName}" TextColor="Black" FontSize="Medium" VerticalOptions="Center"/>
<Label Text="{Binding ItemQuantity}" TextColor="Black" FontSize="Medium" HorizontalOptions="EndAndExpand" VerticalOptions="Center"/>
<CheckBox IsChecked="{Binding MenuStatus}" IsEnabled="{Binding CheckboxEnabled}" HorizontalOptions="End">
<CheckBox.Behaviors>
<prism:EventToCommandBehavior EventName="CheckedChanged" Command="{Binding Path=BindingContext.ChkboxChangedCommand, Source={x:Reference Name=KitchenOrderTicketVM}}" CommandParameter="{Binding}"/>
</CheckBox.Behaviors>
</CheckBox>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</StackLayout>
</Frame>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</ScrollView>
</DataTemplate>
</xct:TabView.TabContentDataTemplate>
</xct:TabView>
I didn't find a way to set the TextColorSelected property in TabViewItemDataTemplate.
For scenarios where you are not sure of the number of TabViewItems, you could try drawing the layout in code behind.
Something like:
public Page10()
{
InitializeComponent();
....
foreach (var item in tabview.TabItemsSource) //here the tabitemsource is a array of strings for test.
{
var tabViewItem = new TabViewItem
{
Text = (string)item,
TextColor = Color.White,
TextColorSelected = Color.Red,
};
var label = new Label
{
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Text = (string)item
};
tabViewItem.Content = label;
tabview.TabItems.Add(tabViewItem);
}
}
define a x:Name for TabView:
<xct:TabView x:Name="tabview" TabItemsSource="{Binding KitchenOrderCollection}" TabStripPlacement="Top" TabStripBackgroundColor="AliceBlue" TabStripHeight="50" IsSwipeEnabled="False" TabIndicatorColor="Black"
AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All" SelectedIndex="{Binding SelectedIdx}">
...
</xct:TabView>

How to do delete button that delete one cell in collection view and row in sqlite in xamarin?

How to delete cell in collection view and row in sqlite?
I need to get from collection view primary key and i dont know how.
I want to have delete button on every view cell.
I have ended up with this:
public void RemovePlane()
{
var db = new SQLiteConnection(_dbPath);
db.Delete<Airplane>();
}
xaml:
<CollectionView x:Name="myCollectionView" Grid.Row="0" SelectedItem="{Binding selectedPlane}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Margin="0">
<Frame Padding="0" BackgroundColor="#00d2ff" Margin="0, 65, 0, 0" CornerRadius="30">
<StackLayout Padding="20">
<Label Text="{Binding Airline}" TextColor ="White" FontSize="30" HorizontalOptions="Center"/>
<Image Source="{Binding ThumbnailUrl}" HeightRequest="200"/>
<Label Text="{Binding Plane, StringFormat='Plane: {0}'}" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Airline, StringFormat='Airline: {0}'}" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Livery, StringFormat='Livery: {0}'}" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Registration, StringFormat='Reg: {0}'}" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Airport, StringFormat='Airport: {0}'}" TextColor ="White" FontSize="15"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0">
<Label Text="{Binding Date, StringFormat='Date: {0}'}" TextColor ="White" FontSize="15"/>
<Label Text="{Binding Comment, StringFormat='Comment: {0}'}" TextColor ="White" FontSize="15"/>
</StackLayout>
<Button Text="Delete" CornerRadius="30" Margin="10, 0" HeightRequest="20" BackgroundColor="Red" Grid.Column="1" x:Name="deleteButton"/>
</Grid>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
<CollectionView.EmptyView>
<AbsoluteLayout VerticalOptions="CenterAndExpand">
<Label FontAttributes="Bold" FontSize="30" TextColor="White" HorizontalTextAlignment="Center" Text="No planes to display" AbsoluteLayout.LayoutBounds="0.5, 0.45, 300, 50" AbsoluteLayout.LayoutFlags="PositionProportional"/>
<Button Text="Import Plane" WidthRequest="10" BackgroundColor="#00d2ff" FontSize="30" FontAttributes="Bold" TextColor="White" CornerRadius="30" VerticalOptions="Center" Padding="5" AbsoluteLayout.LayoutBounds="0.5, 0.55, 280, 70" AbsoluteLayout.LayoutFlags="PositionProportional" Clicked="Button_Clicked"/>
</AbsoluteLayout>
</CollectionView.EmptyView>
</CollectionView>
assign a handler for your button
<Button Text="Delete" Clicked="RemovePlane" ... />
in your handler
public void RemovePlane(object sender, EventArgs args)
{
var button = (Button)sender;
var plane = (Airplane)button.BindingContext;
var db = new SQLiteConnection(_dbPath);
db.Delete<Airplane>(plane);
// finally, either refresh your ItemsSource from your db
// or if you are using an ObservableCollection just remove
// it from the collection
}
I have done this and and when i refresh it works.
One question it delete whole row? And can it be improved somehow?
private void deleteButton_Clicked(object sender, EventArgs e)
{
var button = (Button)sender;
var plane = (Airplane)button.BindingContext;
var db = new SQLiteConnection(_dbPath);
db.Delete<Airplane>(plane.Id);
}

Can someone tell me where I'm going wrong with Binding in Xamarin

Below I've attached snippets of my xaml & cs files. I'm trying to bind the entry boxes to the correct properties & the label is to be binded to the total property. I'm obviously going wrong somewhere I just can't put my finger on where. When using WPF I lay out my binding the same way. I've tried googling this & several videos which none seem to help my problem.
XAML
<Label Text="{Binding Total}"
TextColor="Black"
FontSize="50"
Grid.Column="1"
Grid.ColumnSpan="3"
Grid.Row="4"
Grid.RowSpan="1"
VerticalOptions="Center"
HorizontalOptions="Center"/>
<Label Text="APR Amount"
TextColor="Black"
FontSize="16"
Grid.Column="1"
Grid.ColumnSpan="3"
Grid.Row="5"
Grid.RowSpan="1"
VerticalOptions="Center"
HorizontalOptions="Center"/>
<Label Text="£APR"
TextColor="Black"
FontSize="30"
Grid.Column="1"
Grid.ColumnSpan="3"
Grid.Row="6"
Grid.RowSpan="1"
VerticalOptions="Center"
HorizontalOptions="Center"/>
<BoxView Color="CornflowerBlue"
CornerRadius="0"
Grid.Column="0"
Grid.ColumnSpan="5"
Grid.Row="7"
Grid.RowSpan="1"
WidthRequest="700"
HeightRequest="5"
VerticalOptions="Center"
HorizontalOptions="Center" />
<Label Text="Loan Amount"
TextColor="Black"
FontSize="20"
Grid.Column="0"
Grid.ColumnSpan="3"
Grid.Row="9"
Grid.RowSpan="2"
VerticalOptions="Center"
HorizontalOptions="Center"
Margin="0,0,0,0" />
<Entry Grid.Row="9"
Grid.Column="2"
Grid.ColumnSpan="3"
Grid.RowSpan="2"
WidthRequest="120"
VerticalOptions="Center"
HorizontalOptions="End"
Text="{Binding loanLength}"
Margin="0,0,45,0" />
<Label Text="Interest Rate"
TextColor="Black"
FontSize="20"
Grid.Column="0"
Grid.ColumnSpan="3"
Grid.Row="11"
Grid.RowSpan="2"
VerticalOptions="Center"
HorizontalOptions="Center"
Margin="0,0,0,0" />
<Entry Grid.Row="11"
Grid.RowSpan="2"
Grid.Column="2"
Grid.ColumnSpan="3"
WidthRequest="120"
VerticalOptions="Center"
HorizontalOptions="End"
Text="{Binding intRate}"
Margin="0,0,45,0" />
<Label Text="Loan Length (Years)"
TextColor="Black"
FontSize="20"
Grid.Column="0"
Grid.ColumnSpan="3"
Grid.Row="13"
Grid.RowSpan="2"
VerticalOptions="Center"
HorizontalOptions="Center"
Margin="0,0,0,0" />
<Entry Grid.Row="13"
Grid.RowSpan="2"
Grid.Column="2"
Grid.ColumnSpan="3"
WidthRequest="120"
VerticalOptions="Center"
HorizontalOptions="End"
Text="{Binding loanLength}"
Margin="0,0,45,0"/>
C#
private int loanAmount { get; set; }
public int Loan
{
get => loanAmount;
set
{
loanAmount = value;
OnPropertyChanged("Loan");
CalculateAPR();
}
}
private int intRate { get; set; }
public int Interest
{
get => intRate;
set
{
intRate = value;
OnPropertyChanged("Interest");
CalculateAPR();
}
}
private int loanLength { get; set; }
public int Length
{
get => loanLength;
set
{
loanLength = value;
OnPropertyChanged("Length");
CalculateAPR();
}
}
private string total { get; set; }
public string Total
{
get => total;
set
{
total = value;
OnPropertyChanged("Total");
}
}
public void CalculateAPR()
{
if (Interest != 0)
{
Total = "£" + (Loan * Length) / Interest;
}
else
{
Total = "£ -";
}
}
you need to bind to a public property like "Length" or "Interest"
and call PropertyChanged(nameof(loanLength)); for example (with private inside)
check this if you need
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-binding-basics
I created a demo to simulate your code,and it worked properly.
There are severals problems in your code:
1.We should bind a public property, for example, you can bind like this:
<Entry
Text="{Binding Loan}"
Margin="0,0,45,0" />
Instead of
<Entry
Text="{Binding loanLength}"
Margin="0,0,45,0" />
The same is true of other fields.
Replace <Entry Text="{Binding intRate }"/> with <Entry Text="{Binding Interest}"/>
and
Replace <Entry Text="{Binding loanLength }"/> with <Entry Text="{Binding Length}"/>
2.Try the following bindingContext code:
<Grid >
<Grid.BindingContext>
<local:ViewModel></local:ViewModel>
</Grid.BindingContext>
<Grid.RowDefinitions>
</Grid.RowDefinitions>
<!--other code-->
</Grid>

Identify Auto generating Rows in xamarin forms

I have created a application which create rows dynamically ( automatically ) when the user enter done ( in numeric keypad) . the first row is defined static manner and from the code behind rows will be created automatically followed by the columns according to the predefined columns in the first row .Xaml code as below.
<StackLayout>
<Label Text="SALES ORDER" FontSize="Medium" HorizontalTextAlignment="Center" TextColor="Black" BackgroundColor="White" FontAttributes="Bold" VerticalOptions="Center"></Label>
</StackLayout>
<Grid x:Name="thegrid" RowSpacing="7" ColumnSpacing="1" BackgroundColor="White">
<Grid.RowDefinitions>
<RowDefinition Height="10" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="10" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label x:Name="B1" Text = "ROUTE CODE" Grid.Row="1" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B2" Text = "" Grid.Row="1" Grid.Column="1" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>
<Label x:Name="B3" Text = "SHOP CODE" Grid.Row="1" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B4" Text = "Admin" Grid.Row="1" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>
<Label x:Name="B5" Text = "INVOICE DATE" Grid.Row="2" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<DatePicker x:Name="radDateTimePicker1" MinimumDate="01/01/1990" MaximumDate="01/01/2030" Grid.Row="2" Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center" />
<Label x:Name="B10" Text="{Binding Date, Source={x:Reference radDateTimePicker1},StringFormat='{0:d/M/yyyy HH:mm:ss}'}" Grid.Row="5" Grid.Column="1" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White" />
<!-- <Label x:Name="B15" Text = "AREA" Grid.Row="4" Grid.Column="0" FontSize="Medium" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B25" Text = "UVA" Grid.Row="4" Grid.Column="1" FontSize="Medium" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>-->
<Label x:Name="B35" Text = "SHOP NAME" Grid.Row="5" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B45" Text = "RADHA TRADERS" Grid.Row="5" Grid.Column="1" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>
<Label x:Name="B55" Text = "SALES ORDER" Grid.Row="3" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B65" Text = "HATTON" Grid.Row="3" Grid.Column="1" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>
<Label x:Name="B7" Text = "AGENCY NAME" Grid.Row="2" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Picker x:Name="PickerListtwo" Grid.Row="2" Grid.Column="3" BackgroundColor="White" IsVisible="False" SelectedIndexChanged="PickerList_SelectedIndexChangedtwo">
<Picker.Items>
<x:String>Mohammed R</x:String>
<x:String>Sanath J</x:String>
<x:String>Rahul R</x:String>
<x:String>Mohammed I</x:String>
<x:String>Thuwan A</x:String>
<x:String>Praveen K</x:String>
<x:String>Roshan P</x:String>
</Picker.Items>
</Picker>
<Label x:Name="PickerLabeltwo" Text="CUSTOMER" FontSize="15" Grid.Row="2" Grid.Column="3" HorizontalOptions="Center" HorizontalTextAlignment="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tappedtwo"/>
</Label.GestureRecognizers>
</Label>
<!--<Label x:Name="B9" Text = "" Grid.Row="3" Grid.Column="0" FontSize="Medium" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>-->
<Label x:Name="B11" Text = "AGENCY CODE" Grid.Row="3" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White" />
<Label x:Name="outstanding" Text = "" Grid.Row="3" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Red"/>
<Label x:Name="CRTOP" Text = "AREA" Grid.Row="4" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="CRANS" Text = "" Grid.Row="4" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Red"/>
<Label x:Name="CRBAL" Text = "OPEARTION" Grid.Row="5" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="BALANS" Text = "" Grid.Row="5" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Red"/>
<Label x:Name="ADDRESSN" Text = "ADDRESS" Grid.Row="6" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="ADDRESSV" Text = "" Grid.Row="6" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Red"/>
</Grid>
<Grid x:Name="controlGrid" RowSpacing="2" ColumnSpacing="1.5" BackgroundColor="Black" >
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<!--<RowDefinition Height="50" />-->
<!--<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />-->
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label x:Name="Btn_1" Text = "PRODUCT" Grid.Row="1" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="Btn_2" Text = "QTY" Grid.Row="1" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="Btn_3" Text = "PRICE" Grid.Row="1" Grid.Column="1" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="Btn_4" Text = "FREE ISSUE" Grid.Row="1" Grid.Column="3" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="Btn_5" Text = "UNIT TOTAL" Grid.Row="1" Grid.Column="4" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="PickerLabelthree" Text="1 SELECT PRODUCT" FontSize="12" Grid.Row="2" Grid.Column="0" HorizontalOptions="FillAndExpand" BackgroundColor="White" TextColor="Black" HorizontalTextAlignment="Center" VerticalTextAlignment="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tappedthree"/>
</Label.GestureRecognizers>
</Label>
<Entry x:Name="Qtyone" TextChanged="SetRepairPercent" Keyboard="Numeric" Completed="Qtyone_Completed" Grid.Row="2" Grid.Column="2" BackgroundColor="White" FontSize="15" TextColor="Black" />
<Entry x:Name="Priceoneout" TextChanged="SetRepairPercent" Keyboard="Numeric" Grid.Row="2" Grid.Column="1" BackgroundColor="White" FontSize="15" TextColor="Black" />
<Label x:Name="Totone" Grid.Row="2" Grid.Column="3" BackgroundColor="White" FontSize="15" TextColor="Black" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
<Entry x:Name="TotoneR" TextChanged="SetRepairPercent" Keyboard="Numeric" Grid.Row="2" Grid.Column="4" BackgroundColor="White" FontSize="15" TextColor="Black" />
and the auto generation row code behind as below
private void Qtyone_Completed(object sender, EventArgs e)
{
AddARowToGridView();
// TotoneR.Text = "13.5";
}
int rowCount;
private void AddARowToGridView()
{
Label PickerLabelthree = new Label();
PickerLabelthree.Text = "1 SELECT PRODUCT";
PickerLabelthree.FontSize = 15;
PickerLabelthree.BackgroundColor = Color.White;
PickerLabelthree.TextColor = Color.Black;
PickerLabelthree.HorizontalOptions = LayoutOptions.FillAndExpand;
PickerLabelthree.HorizontalTextAlignment = TextAlignment.Center;
PickerLabelthree.VerticalTextAlignment = TextAlignment.Center;
// PickerLabelthree.Text = pickelabelthr;
// PickerLabelthree.GestureRecognizers.Add(new TapGestureRecognizer((view) => OnLabelClicked()));
// SalesPopup.testing = PickerLabelthree.Text;
PickerLabelthree.GestureRecognizers.Add(new TapGestureRecognizer
{
Command = new Command(() => OnLabelClicked()),
});
//PickerLabelthree.GestureRecognizers.Add() += TapGestureRecognizer_Tappedthree;
Entry Qtyone = new Entry();
Qtyone.Keyboard = Keyboard.Numeric;
Qtyone.BackgroundColor = Color.White;
Qtyone.FontSize = 12;
Qtyone.TextColor = Color.Black;
Qtyone.TextChanged += SetRepairPercent;
Qtyone.Completed += Qtyone_Completed;
Entry Priceoneout = new Entry();
Priceoneout.TextChanged += SetRepairPercent;
Priceoneout.Keyboard = Keyboard.Numeric;
Priceoneout.BackgroundColor = Color.White;
Priceoneout.FontSize = 12;
Priceoneout.TextColor = Color.Black;
Label Totone = new Label();
Totone.BackgroundColor = Color.White;
Totone.FontSize = 12;
Totone.TextColor = Color.Black;
Totone.HorizontalTextAlignment = TextAlignment.Center;
Totone.VerticalTextAlignment = TextAlignment.Center;
Entry TotoneR = new Entry();
TotoneR.Keyboard = Keyboard.Numeric;
TotoneR.BackgroundColor = Color.White;
TotoneR.TextColor = Color.Black;
TotoneR.FontSize = 12;
TotoneR.TextChanged += SetRepairPercent;
//double _qtyoneamount;
//_qtyoneamount = this.Qtyoneans * this.Priceoneans;
//TotoneR.Text = _qtyoneamount.ToString();
controlGrid.Children.Add(PickerLabelthree, 0, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Priceoneout, 1, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Qtyone, 2, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Totone, 3, Convert.ToInt32(rowCount));
controlGrid.Children.Add(TotoneR, 4, Convert.ToInt32(rowCount));
// TotoneR.Text = "13.5";
rowCount++;
}
so the question is , i am unable to identify the details of the cells in rows creating automatically (to get the reference of the column cells) in the newly generating rows.( because the reason want to identify the new column row cells is that we need to calculate the price and quantity to calculate the total value in the last column) . Help will be highly appreciated and thank you in-advance for your support .
Although it's best to use an ObservableCollection instead, the reason your solution is not working is because you are not adding the children to the Grid in the Main/UI Thread. The Qtyone_Completed event handler creates another thread for the execution of the layout change. You can make it work by enclosing those lines in a function like this
Device.BeginInvokeOnMainThread(() =>
{
controlGrid.Children.Add(PickerLabelthree, 0, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Priceoneout, 1, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Qtyone, 2, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Totone, 3, Convert.ToInt32(rowCount));
controlGrid.Children.Add(TotoneR, 4, Convert.ToInt32(rowCount));
});

Debugging: System.DivideByZeroException: Attempted to to divide by zero [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I can't figure out why I am getting this divide by zero exception. I'm very new to programming in general and can't figure out what I'm doing wrong. Sorry for the long code, I think I've removed about as much as possible and have it still give the exception.
Here is the C# 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 CalculationApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BreakEvenCalculation();
}
private void BreakEvenCalculation()
{
var purchaseprice = Decimal.Parse(PurchasePriceEntry.Text);
var purchaseweight = Decimal.Parse(PurchaseWeightEntry.Text);
var purchasefreight = Decimal.Parse(PurchaseFreightEntry.Text);
var medicineimplants = Decimal.Parse(MedicineImplantsEntry.Text);
var costofgain = Decimal.Parse(CostOfGainEntry.Text);
var poundstillsell = Decimal.Parse(PoundsTillSellEntry.Text);
var deathloss = Decimal.Parse(DeathLossEntry.Text);
var saleweight = Decimal.Parse(SaleWeightEntry.Text);
var salefreight = Decimal.Parse(SaleFreightEntry.Text);
var breakeven = Decimal.Parse(BreakEvenEntry.Text);
var purchasedollars = purchaseprice * purchaseweight;
var feedcost = costofgain * poundstillsell;
poundstillsell = saleweight - purchaseweight;
var costs = (purchasedollars + purchasefreight + medicineimplants + feedcost + deathloss + salefreight);
breakeven = costs / saleweight; //throws exception.... System.DivideByZeroException: Attempted to divide by zero
//breakeven = costs / (saleweight + 1); //correctly equals 1.111302549965541
//breakeven = costs * saleweight; //correctly equals 2338125.00
//breakeven = saleweight; //correctly equals 1450.00
//breakeven = costs; //correctly equals 1612.50
////////////breakeven should equal 1.112068965517241
BreakEvenEntry.Text = breakeven.ToString();
}
private void PurchasePriceEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void PurchaseWeightEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void PurchaseFreightEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void MedicineImplantsEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void CostOfGainEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void PoundsTillSellEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void DeathLossEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void SalePriceEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void SaleWeightEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void SaleFreightEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
}
And here is the xaml code...
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="CalculationApp.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CalculationApp"
xmlns:customentry="clr-namespace:CustomEntry">
<StackLayout Padding="0" BackgroundColor="AliceBlue" Orientation="Vertical">
<Label Text="CalculationApp" TextColor="Black" FontAttributes="Italic" FontSize="Large" TextDecorations="Underline" Scale="1.5"
Margin="0,15,0,10" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand"/>
<Grid ColumnSpacing="0" RowSpacing="5">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width=".6*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="Purchase Price" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="0" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap"/>
<Label Text="Purchase Weight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="1" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Purchase Freight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="2" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Medicine/Implants" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="3" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Cost of Gain" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="4" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Pounds Till Sell" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="5" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Death Loss" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="6" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Sale Price" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="7" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Sale Weight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="8" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Sale Freight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="9" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Entry x:Name="PurchasePriceEntry" Text="{Binding Source={x:Reference PurchasePriceStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="0" HorizontalTextAlignment="Center" Keyboard="Numeric" ReturnType="Next" VerticalOptions="End" MaxLength="5"
TextChanged="PurchasePriceEntry_Completed"/>
<Entry x:Name="PurchaseWeightEntry" Text="{Binding Source={x:Reference PurchaseWeightStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="1" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="PurchaseWeightEntry_Completed" />
<Entry x:Name="PurchaseFreightEntry" Text="{Binding Source={x:Reference PurchaseFreightStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="2" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="PurchaseFreightEntry_Completed" />
<Entry x:Name="MedicineImplantsEntry" Text="{Binding Source={x:Reference MedicineImpantsStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="3" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="MedicineImplantsEntry_Completed" />
<Entry x:Name="CostOfGainEntry" Text="{Binding Source={x:Reference CostofGainStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="4" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="CostOfGainEntry_Completed" />
<Entry x:Name="PoundsTillSellEntry" Text="1000" TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="5" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center" IsEnabled="False" />
<Entry x:Name="DeathLossEntry" Text="{Binding Source={x:Reference DeathLossStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="6" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="DeathLossEntry_Completed" />
<Entry x:Name="SalePriceEntry" Text="{Binding Source={x:Reference SalePriceStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="7" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="SalePriceEntry_Completed" />
<Entry x:Name="SaleWeightEntry" Text="{Binding Source={x:Reference SaleWeightStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="8" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="SaleWeightEntry_Completed" />
<Entry x:Name="SaleFreightEntry" Text="{Binding Source={x:Reference SaleFreightStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="9" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="SaleFreightEntry_Completed" />
<Stepper x:Name="PurchasePriceStepper" Grid.Column="2" Grid.Row="0" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5" Minimum=".01" Increment=".01" Value="1.75" />
<Stepper x:Name="PurchaseWeightStepper" Grid.Column="2" Grid.Row="1" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="2000" Minimum="1" Increment="1" Value="550"/>
<Stepper x:Name="PurchaseFreightStepper" Grid.Column="2" Grid.Row="2" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="100" Minimum="0" Increment=".25" Value="10"/>
<Stepper x:Name="MedicineImpantsStepper" Grid.Column="2" Grid.Row="3" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="500" Minimum="0" Increment=".25" Value="25.00"/>
<Stepper x:Name="CostofGainStepper" Grid.Column="2" Grid.Row="4" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="3" Minimum="0" Increment=".01" Value="0.65"/>
<Stepper x:Name="DeathLossStepper" Grid.Column="2" Grid.Row="6" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="500" Minimum="0" Increment="1" Value="20"/>
<Stepper x:Name="SalePriceStepper" Grid.Column="2" Grid.Row="7" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5" Minimum="0" Increment=".01" Value="1.25"/>
<Stepper x:Name="SaleWeightStepper" Grid.Column="2" Grid.Row="8" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5000" Minimum="0" Increment="5" Value="1450.00"/>
<Stepper x:Name="SaleFreightStepper" Grid.Column="2" Grid.Row="9" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="100" Minimum="0" Increment=".25" Value="10"/>
</Grid>
<Grid Padding="10" ColumnSpacing="5" RowSpacing="10" VerticalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Text="Break Even" x:Name="BreakEvenLabel" TextColor="Black" FontSize="Medium" FontAttributes="Bold" Grid.Column="0" Grid.Row="0" HorizontalTextAlignment="Center" VerticalOptions="Center" LineBreakMode="NoWrap" />
<Label Text="Profit" TextColor="Black" FontSize="Medium" FontAttributes="Bold" Grid.Column="1" Grid.Row="0" HorizontalTextAlignment="Center" VerticalOptions="Center" LineBreakMode="NoWrap" />
<Entry x:Name="BreakEvenEntry" Text="125" FontSize="Large" TextColor="Black" Grid.Column="0" Grid.Row="1" FontAttributes="Bold" BackgroundColor="Ivory" IsEnabled="False" HorizontalTextAlignment="Center" VerticalOptions="Center" />
<Entry x:Name="ProfitEntry" TextColor="Black" FontSize="Large" Grid.Column="1" Grid.Row="1" FontAttributes="Bold" BackgroundColor="Ivory" IsEnabled="False" HorizontalTextAlignment="Center" VerticalOptions="Center" />
</Grid>
</StackLayout>
</ContentPage>
The exception happens on this line in C#...
breakeven = costs / saleweight;
As you can see, I've tried changing the code several different ways to try to figure out whats going on. In my mind, to get the divide by zero exception, the saleweight has to be zero but if I change the code to simply read...
breakeven = saleweight;
The Xamarin.Forms BreakEvenEntry gives me the correct sale weight...so it isn't zero right??
What am I missing? What am I doing wrong??
Thanks for the help in advance!!
'Cost' is being created as a float or double and needs to be explicitly defined as decimal to match your parsed decimal variables.
decimal costs = (purchasedollars + [...]
Here is a link on integer vs float division for C#:
"If one of the operands is decimal, another operand can be neither float nor double, because neither float nor double is implicitly convertible to decimal. You must explicitly convert the float or double operand to the decimal type."
(Conversely to the above suggestion, you may consider parsing your variables as doubles or floats. Same result: float division instead of integer division.)
I attempted to reproduce your error, but was unable. I, however, was reminded of a time in Python 2.7 where I found a similar error.

Categories