Reputation: 27
so basically, I ran into a problem, I can't figure out. I have this code:
if ((v - e.Delta) <= 0) vScrollBar1.Value = vScrollBar1.Minimum;
if ((v - e.Delta) >= vScrollBar1.Maximum) vScrollBar1.Value = vScrollBar1.Maximum;
else vScrollBar1.Value -= e.Delta;
Even though the first if statement is true and runs its code, it runs the "else" code anyway. Example: v = 0, e.Delta = 120 so the first if statement is true and works, but I don't know why it runs the else statement anyway, it doesn't run when the second if statement is true. Thank for answers/suggestions!
Upvotes: 0
Views: 267
Reputation: 1193
Both if
s are different. You see, the order for conditionals in C# is if-else if-else
. So, make that second if
an else if
and your logic should function as expected.
if ((v - e.Delta) <= 0) vScrollBar1.Value = vScrollBar1.Minimum;
else if ((v - e.Delta) >= vScrollBar1.Maximum) vScrollBar1.Value = vScrollBar1.Maximum;
else vScrollBar1.Value -= e.Delta;
De rien!
Upvotes: 0
Reputation: 45096
Those two if
s are independent.
if ((v - e.Delta) <= 0) vScrollBar1.Value = vScrollBar1.Minimum;
if ((v - e.Delta) >= vScrollBar1.Maximum) vScrollBar1.Value = vScrollBar1.Maximum;
else vScrollBar1.Value -= e.Delta;
You should add an else
before your second if
. Like this:
if ((v - e.Delta) <= 0) vScrollBar1.Value = vScrollBar1.Minimum;
else if ((v - e.Delta) >= vScrollBar1.Maximum) vScrollBar1.Value = vScrollBar1.Maximum;
else vScrollBar1.Value -= e.Delta;
Upvotes: 1
Reputation: 146559
You were missing initial else
in second line,
but even better is to use ternary operator for this:
vScrollBar1.Value =
v - e.Delta <= 0? vScrollBar1.Minimum:
v - e.Delta >= vScrollBar1.Maximum? vScrollBar1.Maximum:
vScrollBar1.Value - e.Delta;
Upvotes: 0