'Adding numbers from Entry
Hello guys i'm making xamarin.forms app and have two inputs from entries and I need to add the numbers entered into a separate sums every time a button is pressed
x:Name="Player1"
Text="{Binding Player1.Text}"
Style="{StaticResource LabelStyle}"
FontSize="20"
HorizontalOptions="Center"
VerticalTextAlignment="Center"
LineBreakMode="WordWrap"
/>
<Entry Grid.Column="1" Grid.Row="0"
x:Name="scoreEntry1"
Keyboard="Numeric"
FontSize="25"
Placeholder="0"
HorizontalOptions="Fill"
HorizontalTextAlignment="Center"
Margin="0,20,0,0"
/>
<Label Grid.Column="0" Grid.Row="1"
x:Name="Player2"
Text="{Binding Player2.Text}"
Style="{StaticResource LabelStyle}"
FontSize="20"
HorizontalOptions="Center"
VerticalTextAlignment="Center"
LineBreakMode="WordWrap"
/>
<Entry Grid.Column="1" Grid.Row="1"
x:Name="scoreEntry2"
Keyboard="Numeric"
FontSize="25"
Placeholder="0"
HorizontalOptions="Fill"
HorizontalTextAlignment="Center"
Margin="0,20,0,0"
/>
<Grid>
<Button Grid.Column="0" Grid.Row="0"
Text="Next round"
BackgroundColor="#26940F"
TextColor="#FFFFFF"
Clicked="Next_round"
Command="{Binding ButtonNext}">
</Button>
I've tried to do the calculation in the .cs but couldn't figure it out. Can someone help me?
Solution 1:[1]
first, don't use an event and a command on the button - pick one or the other
to add the numbers, do something like this
public void Next_round(object sender, EventArgs args)
{
// use int.Parse if the number are ints, I'm assuming double
var val1 = double.Parse(scoreEntry1.Text);
var val2 = double.Parse(scoreEntry2.Text);
// add them
var sum = val1 + val2;
// you haven't specified what you want to do with the result???
}
note that this is a very basic approach, and very brittle - it will break if the user enters in a string that is not a valid double. To handle this you should add some exception handling (ie, a try/catch block), or use TryParse instead of just Parse. Refer to the C# docs on either of these topics
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jason |
