Solution:
code of the MainWindow.xaml
<Window x:Class="BMICalculator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BMI Calculator" Height="300" Width="400">
<Grid>
<TextBlock Text="VU ID: bc200403911" HorizontalAlignment="Center"
VerticalAlignment="Top" Margin="10" FontSize="14"/>
<Label Content="Weight (kg):" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="50,50,0,0"/>
<Label Content="Height (m):" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="50,100,0,0"/>
<Label Content="BMI:" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="51,175,0,0"/>
<TextBox Name="WeightTextBox" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="150,50,0,0" Width="150"/>
<TextBox Name="HeightTextBox" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="150,100,0,0" Width="150"/>
<TextBox Name="BmiTextBox" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="150,183,0,0" Width="150" IsReadOnly="True"/>
<Button Name="CalculateButton" Content="Calculate BMI" HorizontalAlignment="Center"
VerticalAlignment="Top" Margin="0,142,0,0" Width="100" Click="CalculateButton_Click"/>
</Grid>
</Window>
code of the MainWindow.xaml.cs file
using System;
using System.Windows;
namespace BMICalculator
1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CalculateButton_Click(object sender, RoutedEventArgs e)
{
try
{
// Input validation: Check if weight or height are empty
if (string.IsNullOrWhiteSpace(WeightTextBox.Text) ||
string.IsNullOrWhiteSpace(HeightTextBox.Text))
{
MessageBox.Show("Please enter both weight and height.", "Input Error",
MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
double weight = Convert.ToDouble(WeightTextBox.Text);
double height = Convert.ToDouble(HeightTextBox.Text);
if (height <= 0)
{
MessageBox.Show("Height must be a positive value.", "Input Error",
MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (height > 100)
{
height /= 100;
}
// BMI calculation
double bmi = weight / (height * height);
int bmiInteger = (int)Math.Round(bmi);
2
BmiTextBox.Text = bmiInteger.ToString("F2");
}
catch (FormatException)
{
MessageBox.Show("Please enter valid numeric values for weight and height.", "Input Error",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}