Reputation: 1808
I have 2 sliders in my program. My second slider is never allowed to be less than my first slider, so if someone were to try to slide the second slider down past the first one, the first one would always equal the second one.
I'm coding this in C#, and I don't understand why this code does not work:
//SLIDER 1
private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (slider2.Value <= slider1.Value)
slider1.Value = slider2.Value;
}
XAML - My second slider that the compiler says is null
at runtime:
<Slider Height="22" Margin="128,45,130,0" Name="slider2" VerticalAlignment="Top" Maximum="160" Minimum="1" TickFrequency="1" TickPlacement="BottomRight" Value="50" IsSnapToTickEnabled="True" ValueChanged="slider2_ValueChanged" />
The compiler says NullReferenceException was unhandled by user code
, Object reference not set to an instance of an object
. What do I need to do to get this working?
Thanks.
Upvotes: 0
Views: 789
Reputation: 9242
You are getting this problem because when your page initialized and your XAML control started to render then your slider1_ValueChanged
is being called because you are setting its value to 30
, but your slider2
is still not initialized.
That's why you are getting the error.
Upvotes: 1
Reputation: 4865
Come on, this is an easy one. Basics of programming... O_o
Simply check both controls for null
before using them.
private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (slider1 == null || slider2 == null)
return;
if (slider2.Value <= slider1.Value)
slider1.Value = slider2.Value;
}
Upvotes: 1