I am trying to create a program in VB .NET which two numericupdown buttons should be associated, if value in samp button is changed max should also be controlled and vice a versa. I have written code for it but somehow it is not working perfectly. Please let me what I am missing here.
samp Minimum is set to 50 and Maximum 400; while max Minimum is set is 0 and Maximum 350
Private Sub samp_changed() Handles config_samp.ValueChanged
If config_samp.Value <= 400 And config_samp.Value >= 299 Then
config_max.Value = 150
End If
If config_samp.Value <= 300 And config_samp.Value >= 199 Then
config_max.Value = 250
End If
If config_samp.Value <= 198 And config_samp.Value >= 50 Then
config_max.Value = 350
End If
End Sub
Private Sub max_changed() Handles config_max.ValueChanged
If config_max.Value <= 350 And config_max.Value >= 251 Then
config_samp.Value = 200
End If
If config_max.Value <= 250 And config_max.Value >= 151 Then
config_samp.Value = 300
End If
If config_max.Value <= 150 And config_max.Value >= 101 Then
config_samp.Value = 400
End If
End Sub
CodePudding user response:
When the program executes samp_changed()
, the .Value of config_max
is changed, so it calls max_changed()
, which might change the value of config_samp
, which would mean that samp_changed()
is called, and it gets locked in to one value eventually.
What you need to do is temporarily stop each method from causing the other to be called. You can do that by explicitly removing the handler, changing the value, and adding the handler.
Those If config_max.Value <= 350 And config_max.Value >= 251 Then
, and so on, lines are a bit unwieldy. It would be easier to see what is going on by using a Case
statement, something like this:
Public Class Form1
Private Sub samp_changed(sender As Object, e As EventArgs)
Dim newMaxValue = 0
Dim valueChanged = False
Select Case config_samp.Value
Case 50 To 198
newMaxValue = 350
valueChanged = True
Case 199 To 300
newMaxValue = 250
valueChanged = True
Case 299 To 400
newMaxValue = 150
valueChanged = True
End Select
If valueChanged Then
RemoveHandler config_max.ValueChanged, AddressOf max_changed
config_max.Value = newMaxValue
AddHandler config_max.ValueChanged, AddressOf max_changed
End If
End Sub
Private Sub max_changed(sender As Object, e As EventArgs)
Dim newSampValue = 0
Dim valueChanged = False
Select Case config_max.Value
Case 101 To 150
newSampValue = 400
valueChanged = True
Case 151 To 250
newSampValue = 300
valueChanged = True
Case 251 To 350
newSampValue = 200
valueChanged = True
End Select
If valueChanged Then
RemoveHandler config_samp.ValueChanged, AddressOf samp_changed
config_samp.Value = newSampValue
AddHandler config_samp.ValueChanged, AddressOf samp_changed
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler config_samp.ValueChanged, AddressOf samp_changed
AddHandler config_max.ValueChanged, AddressOf max_changed
End Sub
End Class