0

C# UWP Application XAML (Body Mass Index Calculator - BMI)

I need to take TextBox txtKG.Textand pass it to txtDescription.Text

I'm assuming that i have to create instance of TextBox Class somehow but I'm stuck on this error for 2 days. I have tried many ways but I don't know exackly what to do.

ERROR MESSAGE:

System.NullReferenceException: „Object reference not set to an instance of an object.”

MY XAML segment:

<Slider x:Name="sldKG" HorizontalAlignment="Left" Margin="170,306,0,0" VerticalAlignment="Top" Width="184" ValueChanged="Slider_ValueChanged" Minimum="40" Maximum="150" Value="70"/>

<TextBox x:Name="txtKG" FontSize="18" HorizontalAlignment="Left" Margin="50,310,0,0" VerticalAlignment="Top" TextAlignment="Center" Text="{Binding ElementName=sldKG,Path=Value}"/>

<TextBlock FontSize="18" x:Name="kg" HorizontalAlignment="Left" Margin="121,316,0,0" Text="kg" TextWrapping="Wrap" VerticalAlignment="Top"/>
<Slider x:Name="sldCM" HorizontalAlignment="Left" Margin="170,366,0,0" VerticalAlignment="Top" Width="184" ValueChanged="Slider_ValueChanged" Minimum="145" Maximum="240" Value="170"/>

<TextBlock FontSize="18" x:Name="txtDescription" HorizontalAlignment="Left" Margin="52,499,0,0" Text="Type Your parameters and i wil show Your BMI" TextWrapping="Wrap" VerticalAlignment="Top" Height="96" Width="302" TextAlignment="Center"/>

MyPage.xaml.cs

namespace Kalkulator_BMI_UWP
{   
    public sealed partial class MainPage : Page  
    {            
        public MainPage()
        {
            this.InitializeComponent();
}

private void Slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
txtDescription.Text = txtKG.Text;   // <!-- HERE IS THIS ERROR
       }
Nashmár
  • 364
  • 1
  • 4
  • 20
Kselos Max
  • 13
  • 1
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Camilo Terevinto Apr 16 '18 at 21:49

1 Answers1

1

The problem is with the Slider value changed event, an error occurs since the controls have NOT yet been loaded (TextBlocks in your XAML), and as a workaround (which I do in some of my projects), you can encapsulate the method with a try-catch statement like this:

private void Slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
   try
   {
       txtDescription.Text = txtKG.Text;
   }
   catch { }
}
Red David
  • 61
  • 4