Problem with getting checked items of checkedlistbox

Hi

Please create a form with a CheckedListBox and a RichTextBox. Run code, check/uncheck items in left Checkedlistbox and compare results in right Richtextbox.

Why do I get wrong results? What I'm doing wrong?

Many thanks.
Public Class Form1
 
    Dim strOutput As String
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim strCheckBoxText(2) As String
        For i = 0 To 2
            CheckedListBox1.Items.Add("Item " & i.ToString)
        Next
        FillRichTextBox()
    End Sub
 
    Private Sub CheckedListBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckedListBox1.Click
        FillRichTextBox()
    End Sub
 
    Sub FillRichTextBox()
        strOutput = ""
        For i = 0 To 2
            strOutput = strOutput & CheckedListBox1.GetItemChecked(i).ToString & vbCrLf
        Next
        RichTextBox1.Text = strOutput
    End Sub
 
End Class

Open in new window

pteaAsked:
Who is Participating?
 
karstiemanConnect With a Mentor Commented:
You should change the CheckedListBox1_Click with CheckedListBox1_mouseup.
Here's the new code you should try:


Public Class Form1
    Dim i As Integer = Nothing
    Dim strOutput As String
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim strCheckBoxText(2) As String
        For i = 0 To 2
            CheckedListBox1.Items.Add("Item " & i.ToString)
        Next
        FillRichTextBox()
    End Sub
    Private Sub CheckedListBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles CheckedListBox1.MouseUp
        FillRichTextBox()
    End Sub
    
 
    Sub FillRichTextBox()
        strOutput = ""
        For i = 0 To 2
            strOutput = strOutput & CheckedListBox1.GetItemChecked(i).ToString & vbCrLf
        Next
        RichTextBox1.Text = strOutput
    End Sub
 
  
End Class

Open in new window

0
 
pteaAuthor Commented:
Many thanks, that works.

From other source; also would work:
 (see code)

    Private Sub CheckedListBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckedListBox1.SelectedValueChanged
        FillRichTextBox()
    End Sub

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.