0

I use SetItemChecked method to automatically check the checklistbox but it does not work. Anyone have a look to my code and please give a solution?

Private Sub Check(value As Double)
    If 0 <= value < 20 Then
        Me.CheckedListBox1.SetItemChecked(0, True)
    ElseIf 20 <= value < 40 Then
        Me.CheckedListBox1.SetItemChecked(1, True)
    ElseIf 40 <= value < 60 Then
        Me.CheckedListBox1.SetItemChecked(2, True)
    ElseIf 60 <= value < 80 Then
        Me.CheckedListBox1.SetItemChecked(3, True)
    Else
        Me.CheckedListBox1.SetItemChecked(4, True)
    End If
End Sub

Then I call check(60) and it returns the 1st item check. It is wrong?

An Nguyễn
  • 29
  • 1
  • 3
  • Change your condition Me.CheckedListBox1.ClearSelected() If 0 <= value And value < 20 Then Me.CheckedListBox1.SetItemChecked(0, True) ElseIf 20 <= value And value < 40 Then Me.CheckedListBox1.SetItemChecked(1, True) ElseIf 40 <= value And value < 60 Then Me.CheckedListBox1.SetItemChecked(2, True) ElseIf 60 <= value And value< 80 Then Me.CheckedListBox1.SetItemChecked(3, True) Else Me.CheckedListBox1.SetItemChecked(4, True) End If – ChiragMM Mar 26 '18 at 12:34
  • It is pretty wrong, doesn't "return" anything, doesn't uncheck items and ought to use radio buttons, but not wrong as described. Set a breakpoint and single-step the code. – Hans Passant Mar 26 '18 at 12:34
  • There should be a close-vote-reason "use the debugger" – Tim Schmelter Mar 26 '18 at 12:36

2 Answers2

0

You need to correct your conditions as shown below also Clear

Private Sub Check(value As Double)
        Me.CheckedListBox1.ClearSelected()
        If 0 <= value And value < 20 Then
            Me.CheckedListBox1.SetItemChecked(0, True)
        ElseIf 20 <= value And value  < 40 Then
            Me.CheckedListBox1.SetItemChecked(1, True)
        ElseIf 40 <= value  And value < 60 Then
            Me.CheckedListBox1.SetItemChecked(2, True)
        ElseIf 60 <= value And value< 80 Then
            Me.CheckedListBox1.SetItemChecked(3, True)
        Else
            Me.CheckedListBox1.SetItemChecked(4, True)
        End If
    End Sub
ChiragMM
  • 347
  • 4
  • 12
0

The first If-statement will always evaluate to True.
Because True is converted to 1 and False is converted to 0.

It's getting clearer if you look at this:

If (0 <= value) < 20 Then

So no matter which number is contained in value, the condition will be either...

  • True < 20 ..or...
  • False < 20

For more information see here: Convert Boolean to Integer in VB.NET


So you need to change the conditions like following:

If 0 <= value And value < 20 Then ...
MatSnow
  • 7,357
  • 3
  • 19
  • 31
  • Thanks all guys for your answers. I handle the problems. Thanks MatSnow, ChiragMM. your code is work pretty well. – An Nguyễn Mar 26 '18 at 12:49