none
how to find out checkedlistbox's selected items and non selected items RRS feed

  • Question

  • I have a visual studio 2008 checked list box with n number of items, I want to find out selected items and non selected items using a for next loop,

    And save the status in a sql database. And also want to fetch the saved data from sql database and set the status accordingly.

    Please help me to resolve this.

    Thank you.


    Wednesday, June 5, 2019 3:57 PM

Answers

  • Hi,

    I made a demo,Checkedlistbox is associated with a table in the database

    Imports System.Data.SqlClient
    Public Class Form1
        Dim constr As String = "Data Source = (localdb)\MSSQLLocalDB; Integrated Security = True ;AttachDbFileName= C:\Users\alexl2\Desktop\DataBase\Alex\alex.mdf"
        Dim conn As SqlConnection
        Dim sda As SqlDataAdapter
        Dim dt As DataTable
        Dim bind As New BindingSource
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            CheckedListBox1.Items.Clear()
            CheckedListBox1.CheckOnClick = True
            Dim conn = New SqlConnection(constr)
            conn.Open()
            sda = New SqlDataAdapter("Select * From TbChecked", conn)
            Dim SQLCommandBuild As SqlCommandBuilder = New SqlCommandBuilder(sda)
            dt = New DataTable()
            sda.Fill(dt)
            bind.DataSource = dt
            For i = 0 To dt.Rows.Count - 1
                CheckedListBox1.Items.Add("item" & i + 1)
                CheckedListBox1.SetItemChecked(i, dt.Rows(i)(1))
                ListBox1.Items.Add(CheckedListBox1.GetItemChecked(i))
            Next
        End Sub
    
    
        Private Sub CheckedListBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles CheckedListBox1.SelectedValueChanged
            ListBox1.Items.RemoveAt(CheckedListBox1.SelectedIndex)
            ListBox1.Items.Insert(CheckedListBox1.SelectedIndex, CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex))
            dt.Rows(CheckedListBox1.SelectedIndex).Item(1) = CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex)
            bind.EndEdit()
            sda.Update(dt)
        End Sub
    End Class
    

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Niroshan2019 Thursday, June 6, 2019 4:36 AM
    Thursday, June 6, 2019 3:26 AM
  • eureka!!

    Dear Alex!

    This is exactly what I need!  

    I did modify some of the cording and you may find the exact code listed below;

    da1 = New SqlDataAdapter("Select * From tblSettings where UserID='" & UID & "'", Cnn)
            dt1 = New DataTable
            da1.Fill(dt1)

            If dt1.Rows.Count > 0 Then
                Dim cIndex As Integer ' Holds check box item index
                Dim chkStat As Integer ' Holds check box checked state 

                'Clearing all chk marks
                For i As Integer = 0 To 7
                    CheckedListBox1.SetItemCheckState(cIndex, CheckState.Unchecked)
                Next

                'Setting up new CheckState
                For i As Integer = 0 To 7
                    cIndex = dt1.Rows(i)("ctrlIndex")
                    chkStat = dt1.Rows(i)("checkstatus")
                    If chkStat > 0 Then
                       CheckedListBox1.SetItemCheckState(cIndex, CheckState.Checked)
                    Else
                        CheckedListBox1.SetItemCheckState(cIndex, CheckState.Unchecked)
                    End If
                Next

            End If


    Thursday, June 6, 2019 4:32 AM

All replies

  • Hello,

    I have a code sample you can look at here which shows how to populate a CheckedListBox from SQL-Server and update the database table. There is only one issue, all code is in VS2015 but if you follow the code it should be easy to adapt to your VS2008 project.

    For instance, this will not work in VS2008 as language extensions require a higher version of the Framework.

    Public Module CheckedListBoxExtensions 
        ''' <summary> 
        ''' Get description for an item by index in the CheckedListBox 
        ''' </summary> 
        ''' <param name="sender"></param> 
        ''' <param name="Index"></param> 
        ''' <returns></returns> 
        <System.Runtime.CompilerServices.Extension> 
        Public Function Description(ByVal sender As CheckedListBox, ByVal Index As Integer) As String 
            Return CType(sender.Items(Index), CheckListBoxItem).Description 
        End Function 
        ''' <summary> 
        ''' Get primary key for an item by index in the CheckedListBox 
        ''' </summary> 
        ''' <param name="sender"></param> 
        ''' <param name="Index"></param> 
        ''' <returns></returns> 
        <System.Runtime.CompilerServices.Extension> 
        Public Function PrimaryKey(ByVal sender As CheckedListBox, ByVal Index As Integer) As Integer 
            Return CType(sender.Items(Index), CheckListBoxItem).PrimaryKey 
        End Function 
     
    End Module 
    

    Usage someCheckedListBox(10).Description.

    To make this work

    Public Module CheckedListBoxExtensions 
        ''' <summary> 
        ''' Get description for an item by index in the CheckedListBox 
        ''' </summary> 
        ''' <param name="sender"></param> 
        ''' <param name="Index"></param> 
        ''' <returns></returns> 
        Public Function Description(ByVal sender As CheckedListBox, ByVal Index As Integer) As String 
            Return CType(sender.Items(Index), CheckListBoxItem).Description 
        End Function 
        ''' <summary> 
        ''' Get primary key for an item by index in the CheckedListBox 
        ''' </summary> 
        ''' <param name="sender"></param> 
        ''' <param name="Index"></param> 
        ''' <returns></returns> 
        Public Function PrimaryKey(ByVal sender As CheckedListBox, ByVal Index As Integer) As Integer 
            Return CType(sender.Items(Index), CheckListBoxItem).PrimaryKey 
        End Function 
     
    End Module 
    Description(someCheckedListBox,10)


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, June 5, 2019 4:56 PM
    Moderator
  • Hi

    Here is another approach.

    I do not have/use any database stuff at all, so I have just written/read from an XML file, In your case, you would save/read the DataTable to your DB. The DataTable ("Freddy") holds the CheckedItems list.

    Here is my example (stand alone test project.)

    Image

    Code

    Option Strict On
    Option Explicit On
    Public Class Form1
    	Dim WithEvents clb As New CheckedListBox
    	Dim lb As New ListBox
    	Dim rand As New Random
    	Dim ChangeDetected As Boolean = False
    	Dim CheckedItems As New DataTable("Freddy") 'List(Of Integer)
    	Dim BS As New BindingSource()
    	Dim fn As String = Application.StartupPath & "\Data\CheckedList.txt"
    	Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    		' Here you can save the
    		' the DataTable CheckedItems
    		' to your DB
    		' I just save to a FILE
    		CheckedItems.WriteXml(fn)
    	End Sub
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		With CheckedItems
    			.Columns.Add("Index")
    		End With
    		' Here you would have
    		' the checked items from
    		' your DB
    		' I just load from FILE
    		CheckedItems.ReadXml(fn)
    		With clb
    			.Location = New Point(8, 8)
    			.Size = New Size(120, ClientSize.Height - 50)
    			.Font = New Font("Arial", 14)
    			.Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom
    			.IntegralHeight = False
    			For i As Integer = 0 To 9
    				Dim r As Integer = rand.Next(0, 2)
    				If CheckedItems.Select("Index = '" & i & "'").ToList.Count > 0 Then
    					.Items.Add("Item" & i.ToString, True)
    				Else
    					.Items.Add("Item" & i.ToString, False)
    				End If
    			Next
    		End With
    		With lb
    			.Location = New Point(clb.Right + 10, 8)
    			.Size = New Size(100, ClientSize.Height - 50)
    			.Font = New Font("Arial", 14)
    			.Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom
    			.IntegralHeight = False
    		End With
    		Controls.AddRange({clb, lb})
    		BS.DataSource = CheckedItems
    		lb.DataSource = BS
    		lb.DisplayMember = "Index"
    	End Sub
    	Private Sub ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles clb.ItemCheck
    		ChangeDetected = True
    	End Sub
    	Private Sub clb_SelectedIndexChanged(sender As Object, e As EventArgs) Handles clb.SelectedIndexChanged
    		If ChangeDetected Then
    			CheckedItems.Clear()
    			For Each ind As Integer In clb.CheckedIndices
    				CheckedItems.Rows.Add(ind)
    			Next
    			BS.ResetBindings(False)
    		End If
    		ChangeDetected = False
    	End Sub
    End Class


    Regards Les, Livingston, Scotland


    • Edited by leshay Wednesday, June 5, 2019 6:54 PM
    Wednesday, June 5, 2019 6:53 PM
  • Hi,

    Thank you so much for your quick reply and your efforts to  help me on this.

    My problem is I do not want to dynamically load check box items, those items can be setup at the design time, I only need to retrieve/fetch the checked status   (checked or unchecked) by the user, those results needed to be stored in an db and and next time user open his application all previously marked check boxes have to marked "checked"

    Any way a big "thank you" again for your help.

    Rgds,

    Niroshan.

    Thursday, June 6, 2019 2:49 AM
  • Dear Les,

    Thank you so much for this solution, 

    Let me try on this, I think I may use this code. 

    Again Big "Thank you" form the other side of the world :) I'll post my code here once I done.

    Regards,

    Niroshan

    Thursday, June 6, 2019 3:21 AM
  • Hi,

    I made a demo,Checkedlistbox is associated with a table in the database

    Imports System.Data.SqlClient
    Public Class Form1
        Dim constr As String = "Data Source = (localdb)\MSSQLLocalDB; Integrated Security = True ;AttachDbFileName= C:\Users\alexl2\Desktop\DataBase\Alex\alex.mdf"
        Dim conn As SqlConnection
        Dim sda As SqlDataAdapter
        Dim dt As DataTable
        Dim bind As New BindingSource
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            CheckedListBox1.Items.Clear()
            CheckedListBox1.CheckOnClick = True
            Dim conn = New SqlConnection(constr)
            conn.Open()
            sda = New SqlDataAdapter("Select * From TbChecked", conn)
            Dim SQLCommandBuild As SqlCommandBuilder = New SqlCommandBuilder(sda)
            dt = New DataTable()
            sda.Fill(dt)
            bind.DataSource = dt
            For i = 0 To dt.Rows.Count - 1
                CheckedListBox1.Items.Add("item" & i + 1)
                CheckedListBox1.SetItemChecked(i, dt.Rows(i)(1))
                ListBox1.Items.Add(CheckedListBox1.GetItemChecked(i))
            Next
        End Sub
    
    
        Private Sub CheckedListBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles CheckedListBox1.SelectedValueChanged
            ListBox1.Items.RemoveAt(CheckedListBox1.SelectedIndex)
            ListBox1.Items.Insert(CheckedListBox1.SelectedIndex, CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex))
            dt.Rows(CheckedListBox1.SelectedIndex).Item(1) = CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex)
            bind.EndEdit()
            sda.Update(dt)
        End Sub
    End Class
    

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Niroshan2019 Thursday, June 6, 2019 4:36 AM
    Thursday, June 6, 2019 3:26 AM
  • eureka!!

    Dear Alex!

    This is exactly what I need!  

    I did modify some of the cording and you may find the exact code listed below;

    da1 = New SqlDataAdapter("Select * From tblSettings where UserID='" & UID & "'", Cnn)
            dt1 = New DataTable
            da1.Fill(dt1)

            If dt1.Rows.Count > 0 Then
                Dim cIndex As Integer ' Holds check box item index
                Dim chkStat As Integer ' Holds check box checked state 

                'Clearing all chk marks
                For i As Integer = 0 To 7
                    CheckedListBox1.SetItemCheckState(cIndex, CheckState.Unchecked)
                Next

                'Setting up new CheckState
                For i As Integer = 0 To 7
                    cIndex = dt1.Rows(i)("ctrlIndex")
                    chkStat = dt1.Rows(i)("checkstatus")
                    If chkStat > 0 Then
                       CheckedListBox1.SetItemCheckState(cIndex, CheckState.Checked)
                    Else
                        CheckedListBox1.SetItemCheckState(cIndex, CheckState.Unchecked)
                    End If
                Next

            End If


    Thursday, June 6, 2019 4:32 AM