Identify Auto generating Rows in xamarin forms - c#

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));
});

Related

Xamarin forms iOS app, Command button not firing when pressed

I have tried everything I could find on the internet and still cannot get the event to fire. My page contains 2 buttons as you can see which fire in the Simulator but not on my iphone. I have tried many different solutions found on the internet and the one I am showing here is the last one I attempted.
Here is the buttons defined in my view:
<Button Command="{Binding Source={RelativeSource AncestorType={x:Type ViewModel:EditViewModel}}, Path=UpdateMileage}" CommandParameter="{Binding .}" IsEnabled="True" Text="Update" BackgroundColor="Yellow" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="1" TextColor="Black" Margin="4"/>
<Button Command="{Binding Source={RelativeSource AncestorType={x:Type ViewModel:EditViewModel}}, Path=Cancel}" CommandParameter="{Binding .}" Text="Cancel" BackgroundColor="Yellow" Grid.Row="6" Grid.Column="2" Grid.ColumnSpan="2" TextColor="Black" Margin="4"/>
The viewModel code is as follows;
public ICommand UpdateMileage
{
get; set;
}
public EditViewModel()
{
UpdateMileage = new Command(UpdateMileageData);
MileageTableDefination mileage = new MileageTableDefination();
mileage = Application.Current.Properties["MileageData"] as MileageTableDefination;
SDate = Convert.ToDateTime(mileage.Date);
EntMiles = mileage.Miles.ToString();
EntGas = mileage.Gas.ToString();
EntCost = mileage.Price.ToString();
if (mileage.Note != null)
EntNote = mileage.Note.ToString();
EntId = mileage.Id;
}
public async void UpdateMileageData()
{
Analytics.TrackEvent("In UpdateMileageData Top ");
int autoId = Convert.ToInt32(Application.Current.Properties["autoId"]);
//Analytics.TrackEvent("Mileage Data in Enter Mileage: AutoId " + autoId);
error = false;
IsVisibleLabel = false;
if (EntMiles == "0" || EntMiles == null)
{
error = true;
IsVisibleLabel = true;
EntError = "Miles Driven Must Be Numeric";
}
else if (!System.Text.RegularExpressions.Regex.IsMatch(EntMiles, #"^[0-9]\d*(\.\d+)?$"))
{
error = true;
IsVisibleLabel = true;
EntError = "Miles Driven Must Be Numeric";
}
else if (Convert.ToDecimal(EntMiles) > 1000)
{
error = true;
//IsVisibleLabel = true;
EntError = "Miles Driven Since Last Fillup";
}
if (EntGas == "0" || EntGas == null)
{
error = true;
IsVisibleLabel = true;
EntError = "Gas Used Must Be Numeric";
}
else if (!System.Text.RegularExpressions.Regex.IsMatch(EntGas, #"^[0-9]\d*(\.\d+)?$"))
{
error = true;
IsVisibleLabel = true;
EntError = "Gas Used Must Be Numeric";
}
if (EntCost == "0" || EntCost == null)
{
error = true;
IsVisibleLabel = true;
EntError = "Cost Must Be Numeric";
}
else if (!System.Text.RegularExpressions.Regex.IsMatch(EntCost, #"^[0-9]\d*(\.\d+)?$"))
{
error = true;
IsVisibleLabel = true;
EntError = "Cost Must Be Numeric";
}
else if (Convert.ToDecimal(EntCost) > 300.00m)
{
error = true;
IsVisibleLabel = true;
EntError = "Cost Must Be Numeric And < $300";
}
Analytics.TrackEvent("In UpdateMileageData After If's Error = " + error);
if (!error)
{
miles.Date = SDate.Date;
miles.StrDate = SDate.Date.ToString("MM/dd/yyyy");
miles.Miles = Convert.ToDecimal(EntMiles);
miles.Gas = Convert.ToDecimal(EntGas);
miles.Id = EntId;
miles.CarId = autoId;
miles.MPG = Math.Round(Convert.ToDecimal(EntMiles) / Convert.ToDecimal(EntGas), 3);
miles.Price = Convert.ToDecimal(EntCost);
miles.Note = EntNote;
MileageItemRepository mir = new MileageItemRepository();
var results = await mir.UpdateMileageAsync(miles);
Analytics.TrackEvent("In UpdateMileageData Results = " + results);
if (results == 1)
{
Application.Current.Properties["UpdatedData"] = miles;
var nav = MyNavigation.GetNavigation();
await nav.PushAsync(new ViewMileage());
}
}
}
As you can see from my code I have logging statements and they are never reached. Any help would be much appreciated. Thanks in advance!
EDIT:
Here is the full xaml that contains the buttons
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:Validate="clr-namespace:MileageManagerForms.Validators"
xmlns:ViewModel ="clr-namespace:MileageManagerForms.ViewModels"
x:Class="MileageManagerForms.Views.EditMileage">
<ContentPage.BindingContext>
<ViewModel:EditViewModel/>
</ContentPage.BindingContext>
<Grid BackgroundColor="Purple">
<Grid.RowDefinitions>
<RowDefinition Height="47"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="30"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="85"/>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="15"/>
<ColumnDefinition Width="85"/>
<ColumnDefinition Width="40"/>
</Grid.ColumnDefinitions>
<Frame BackgroundColor="#2196F3" Padding="10" CornerRadius="0" Grid.ColumnSpan="7" Grid.Row="0">
<Label Text="Edit Mileage" HorizontalTextAlignment="Center" TextColor="White" FontSize="25" />
</Frame>
<DatePicker x:Name="sDate" Format="MM/dd/yyyy" Date="{Binding SDate}" BackgroundColor="Gray" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" TextColor="White"/>
<Label Text="{Binding EntError}" FontAttributes="Bold" TextColor="Yellow" FontSize="Small" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="6" />
<Label Text="Miles:" TextColor="White" FontSize="Small" Grid.Row="3" Grid.Column="0" Margin="9" />
<Entry Text="{Binding EntMiles}" Keyboard="Numeric" FontSize="Small" BackgroundColor="White" TextColor="Black" Grid.Row="3" Grid.Column="1" Margin="8" >
<Entry.Behaviors>
<Validate:MaxLengthValidator MaxLength="6"/>
<Validate:DecimalValidator />
</Entry.Behaviors>
</Entry>
<Label Text="Gas:" TextColor="White" FontSize="Small" Grid.Row="4" Grid.Column="0" Margin="12" Grid.ColumnSpan="2"/>
<Entry Text="{Binding EntGas}" Keyboard="Numeric" FontSize="Small" BackgroundColor="White" TextColor="Black" Grid.Row="4" Grid.Column="1" Margin="8" >
<Entry.Behaviors>
<Validate:MaxLengthValidator MaxLength="6"/>
<Validate:DecimalValidator />
</Entry.Behaviors>
</Entry>
<Label Text="Cost:" TextColor="White" FontSize="Small" Grid.Row="3" Grid.Column="2" Grid.ColumnSpan="3" Margin="9"/>
<Entry Text="{Binding EntCost}" Keyboard="Numeric" FontSize="Small" BackgroundColor="White" TextColor="Black" Grid.Row="3" Grid.Column="3" Grid.ColumnSpan="2" Margin="8" >
<Entry.Behaviors>
<Validate:MaxLengthValidator MaxLength="7"/>
<Validate:DecimalValidator />
</Entry.Behaviors>
</Entry>
<Label Text="Note:" TextColor="White" FontSize="Small" Grid.Row="4" Grid.Column="2" Margin="10" Grid.ColumnSpan="2" HorizontalTextAlignment="Start"/>
<Entry Text="{Binding EntNote}" Keyboard="Default" FontSize="Small" BackgroundColor="White" TextColor="Black" Grid.Row="4" Grid.Column="3" Grid.ColumnSpan="4" Margin="8">
<Entry.Behaviors>
<Validate:MaxLengthValidator MaxLength="20"/>
</Entry.Behaviors>
</Entry>
<Entry Text="{Binding EntId}" Grid.Row="4" Grid.Column="8" Grid.ColumnSpan="2" Margin="8" IsVisible="false"/>
<Button Command="{Binding Source={RelativeSource AncestorType={x:Type ViewModel:EditViewModel}}, Path=UpdateMileage}" CommandParameter="{Binding .}" IsEnabled="True" Text="Update" BackgroundColor="Yellow" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="1" TextColor="Black" Margin="4"/>
<Button Command="{Binding Source={RelativeSource AncestorType={x:Type ViewModel:EditViewModel}}, Path=Cancel}" CommandParameter="{Binding .}" Text="Cancel" BackgroundColor="Yellow" Grid.Row="6" Grid.Column="2" Grid.ColumnSpan="2" TextColor="Black" Margin="4"/>
</Grid>
As for the question about the binding in the view code behind, I have this;
BindingContext = new EditViewModel();

Remove item using the same button

I'm having an issue figuring out how to remove an item from my project while using the same button as I use to perform another task. To sum it up, I'm working on a project where I have a bunch of events a user can like/dislike. What I'm having issues with is trying to figure out how to remove the event from my project once the user has liked the event using the 'like' button. Essentially I want the 'like' button to perform 2 things, one being when its pressed setting it to "true" which is already doing that, but also I want it to remove the event from screen once it's liked.
Here is my XAML:
<StackLayout VerticalOptions="FillAndExpand">
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image x:Name="LblEventImage"
Aspect="Fill"
HeightRequest="350" />
<BoxView BackgroundColor="Black"
HeightRequest="350"
Opacity="0.3" />
<Image Source="BackIconOrg.png"
Margin="5,40,0,0"
HorizontalOptions="Start"
VerticalOptions="Start"
Grid.Row="0">
<Image.GestureRecognizers>
<TapGestureRecognizer x:Name="ImgBack" Tapped="backButton_Clicked"/>
</Image.GestureRecognizers>
</Image>
</Grid>
<Frame VerticalOptions="FillAndExpand"
IsClippedToBounds="False"
BackgroundColor="#263A4F"
Margin="0,-40,0,0"
CornerRadius="25"
HasShadow="False">
<StackLayout Margin="0,-50,0,0">
<Grid HeightRequest="200"
VerticalOptions="Start">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4*" />
<ColumnDefinition Width="6*"/>
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0"
Padding="5"
Spacing="5"
Margin="0,40,0,0">
<Label x:Name="LblEventName"
TextColor="#fc4600"
FontSize="Large"
FontFamily="TTBold"
FontAttributes="Bold"/>
<StackLayout Orientation="Horizontal"
Spacing="0">
<Frame BackgroundColor="#8B93A6"
BorderColor="#8B93A6"
Padding="8"
CornerRadius="15">
<Label TextColor="White"
x:Name="LblEventCategory"
FontFamily="TTNorms"/>
</Frame>
</StackLayout>
<StackLayout Orientation="Vertical" Grid.ColumnSpan="3">
<Label x:Name="LblEventCity"
TextColor="White"
FontFamily="TTNorms"/>
<Label x:Name="LblEventState"
TextColor="White"
FontFamily="TTNorms"/>
</StackLayout>
<!--<Label x:Name="LblLanguage"
TextColor="White" />
<Label x:Name="LblDuration"
TextColor="White" />-->
</StackLayout>
</Grid>
<Label Text="Details:"
FontSize="Medium"
Margin="0,20,0,0"
TextColor="White"
FontFamily="TTNorms"/>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.65*" />
<ColumnDefinition Width="0.35*" />
</Grid.ColumnDefinitions>
<Label Text="Scheduled Date:"
TextColor="White"
Grid.Row="0"
Grid.Column="0"
FontFamily="TTNorms"/>
<Label Text="August 20, 2021"
TextColor="#8B93A6"
Grid.Row="1"
Grid.Column="0"
FontFamily="TTNorms"/>
<Label Text="Group Size:"
TextColor="White"
Grid.Row="0"
Grid.Column="1"
FontFamily="TTNorms"/>
<Label x:Name="LblEventGroupSize"
TextColor="#8B93A6"
Grid.Row="1"
Grid.Column="1"
FontFamily="TTNorms"/>
<Label Text="Paid:"
TextColor="White"
Grid.Row="2"
Grid.Column="0"
FontFamily="TTNorms"/>
<Label x:Name="LblEventPay"
TextColor="#8B93A6"
Grid.Row="3"
Grid.Column="0"
FontFamily="TTNorms"/>
</Grid>
<BoxView BackgroundColor="#8B93A6"
HeightRequest="1" />
<Label Text="Description"
TextColor="White"
FontFamily="TTNorms"/>
<Label x:Name="LblEventDescription"
TextColor="#8B93A6"
FontFamily="TTNorms"/>
<StackLayout Orientation="Horizontal"
HorizontalOptions="Center"
VerticalOptions="Center"
Spacing="60"
Margin="0,30,0,0">
<Image Source="LikeButton.png"
HeightRequest="150">
<Image.GestureRecognizers>
<TapGestureRecognizer x:Name="likedevent" Tapped="likeButton_Clicked" />
</Image.GestureRecognizers>
</Image>
<Image Source="DislikeButton.png"
HeightRequest="150">
<Image.GestureRecognizers>
<TapGestureRecognizer x:Name="dislikeevent" Tapped="dislikeevent_Tapped"/>
</Image.GestureRecognizers>
</Image>
</StackLayout>
</StackLayout>
</Frame>
</StackLayout>
</ContentPage.Content>
CS:
public partial class MatchDetail : ContentPage
{
private Event event1;
public MatchDetail(int eventId)
{
InitializeComponent();
GetEventDetail(eventId);
}
private async void GetEventDetail(int eventId)
{
event1 = await ApiService.GetEventById(eventId);
LblEventName.Text = event1.Name;
LblEventDescription.Text = event1.Description;
LblEventCity.Text = event1.City;
LblEventImage.Source = event1.FullImageUrl;
LblEventCategory.Text = event1.Category;
LblEventState.Text = event1.State;
LblEventGroupSize.Text = event1.GroupSize.ToString();
LblEventPay.Text = event1.PayTrueFalse;
}
private async void likeButton_Clicked(object sender, EventArgs e)
{
var likedEvent = new Result()
{
Name = LblEventName.Text,
UserId = Preferences.Get("userId", 0),
LikeTrueFalse = "True"
};
if (event1.LikeTrueFalse == "True")
{
//RemoveEvent
}
var response = await ApiService.LikedEvents(likedEvent);
if (response)
{
await DisplayAlert("", "Your event has been liked", "Ok");
}
else
{
await DisplayAlert("Oops", "something went wrong", "cancel");
}
}
private void backButton_Clicked(object sender, EventArgs e)
{
Navigation.PopModalAsync();
}
in your main page
MessagingCenter.Subscribe<object, int>(this, "RemoveEvent", (sender,id) =>
{
// do whatever to remove event "id" here
});
then in your detail page, after you have marked it as a favorite
Messaging.Center.Send<object, int>(this, "RemoveEvent", eventId);

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>

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