Checkedlistbox question

Ron399 0 Reputation points
2023-04-02T20:01:54.95+00:00

How do I get/set the selected index in a checkedlistbox? I need to go through each item and read the text. I also need to check and/or uncheck each item.

thanks in advance.

Developer technologies | VB
{count} votes

1 answer

Sort by: Most helpful
  1. LesHay 7,141 Reputation points
    2023-04-02T21:48:11.97+00:00

    Here is a stand alone example. If you want to try it out, start a new test project, add CheckedListBox1, Label1, Label2, CheckBox1, TextBox1 to Form1 in Designer, then copy/replace the default code with the code below.

    I have tried to show getting index of selected item (can be done for ALL those selected if needed), check/uncheck selected item, find item via text typed into TextBox1. Not exactly in depth, and no error checking catered for.

    Anyway here it is.

    111

    Option Strict On
    Option Explicit On
    Public Class Form1
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		' set up some dummy data for this example
    		For i As Integer = 1 To 10
    			CheckedListBox1.Items.Add("Item " & i.ToString)
    		Next
    	End Sub
    	Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    		' get index for typed string in list
    		' and select it if found
    		Dim i As Integer = CheckedListBox1.FindString(TextBox1.Text)
    		If i > -1 Then
    			' found it, put index in Label2 and
    			' changed selected item to found item
    			Label2.Text = i.ToString
    			CheckedListBox1.SelectedIndex = i
    		End If
    	End Sub
    	Private Sub CheckedListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CheckedListBox1.SelectedIndexChanged
    		' index has changed, put it in Label2
    		Label2.Text = CheckedListBox1.SelectedIndex.ToString
    	End Sub
    	Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
    		Dim chb As CheckBox = DirectCast(sender, CheckBox)
    		' checkbox1 checked state has been
    		' toggled so toggle list selected item
    		CheckedListBox1.SetItemChecked(CheckedListBox1.SelectedIndex, chb.Checked)
    	End Sub
    End Class
    
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.