Click here to Skip to main content
15,034,432 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to display and save records within datagridview with checkedlist box using vb2005.

actually I had create custom control for datagridviewcheckedlistbox and it show data of checked list box with other data retrieve from sql table.
but problem is that when I check items of this checkedlist box and move other row of datagridview this check state removes from all previous checking.

here is my code.
VB
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Data
Imports System.Data.SqlClient
Imports System.Collections
Imports System.Collections.Generic
''' <summary>
Imports System.Object
Imports System.MarshalByRefObject
Imports System.ComponentModel.Component
Imports System.Windows.Forms.Control
Imports System.Windows.Forms.ListControl
Imports System.Windows.Forms.ListBox
Imports System.Windows.Forms.CheckedListBox
''' </summary>
''' <remarks></remarks>

Public Class AddTextboxRunTime
    Public abc As New DataGridView

  
    Private WithEvents CheckedListBox1 As WindowsApplication27.CheckedListBoxEditingControl
    Public ds As New DataSet
    Public adap As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
    Dim chkedlist As New CheckedListBox

    Public Con As New SqlConnection("Server=192.168.0.232;database=DKA;UID=as;PWD=humtum")
    Private Sub AddTextboxRunTime_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      
       

        mstrsql = "select code as 'Column2',Description as 'Column3'  from  dka.dbo.Languagemaster "
        If (gfnintFillDataSet(mstrsql, "Language", ds, Con)) > 0 Then

            DataGridView1.DataSource = ds.Tables("Language")


            Dim str() As String = Split("abc,bcd,def,ghi", ",")

            CheckedListBox1 = New WindowsApplication27.CheckedListBoxEditingControl
            abcd = New WindowsApplication27.CheckedListBoxEditingControl

            For inti = 0 To UBound(str)
                CheckedListBox1.Items.Add(str(inti))
                abcd.Items.Add(str(inti))
            Next

            Dim headerHeight As Integer = DataGridView1.ColumnHeadersHeight

            For inti = 0 To DataGridView1.Rows.Count - 1
                'DataGridView1.Rows(Inti).Cells(0).Value = str
                DataGridView1.Rows(Inti).Cells(0).Value = str

                DataGridView1.Rows(Inti).Height = CheckedListBox1.Height
            Next
           
           
        End If
   
    Dim rec As Rectangle
  

    Private Sub DataGridView1_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
        Try
            Me.Cursor = Cursors.WaitCursor
           

            Me.DataGridView1.Rows(Me.DataGridView1.CurrentCell.RowIndex).ErrorText = ""

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MessageBox.Show(ex.Message, "DKA BALAJI -" & Me.Text, _
            MessageBoxButtons.OK, MessageBoxIcon.Error)

        Finally
            Me.Cursor = Cursors.Default

        End Try
    End Sub

    Private Sub DataGridView1_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit

        Try
            Me.Cursor = Cursors.WaitCursor
           

            Me.DataGridView1.Rows(Me.DataGridView1.CurrentCell.RowIndex).ErrorText = ""

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MessageBox.Show(ex.Message, "DKA BALAJI -" & Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)

        Finally
            Me.Cursor = Cursors.Default

        End Try
    End Sub

    Private Sub DataGridView1_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
        Try
            Me.Cursor = Cursors.WaitCursor

            e.Cancel = True
            Me.DataGridView1.Rows(Me.DataGridView1.CurrentCell.RowIndex).ErrorText = e.Context.ToString() + ";" + e.Exception.Message

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MessageBox.Show(ex.Message, "DKA BALAJI -" & Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)

        Finally
            Me.Cursor = Cursors.Default

        End Try
    End Sub

    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        CheckedListBox1 = DataGridView1.Columns(0).DataGridView.EditingControl
    End Sub

    Public intenterrowindex As Integer

    Private Sub DataGridView1_RowEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowEnter
        If abcd.Items.Count > 0 Then
            If intleaverowindex = DataGridView1.CurrentRow.Index Then
                If abcd.Items.Count > 0 Then
                    For inti = 0 To abcd.Items.Count - 1

                        If abcd.GetItemCheckState(inti) = CheckState.Checked Then
                            CheckedListBox1.SetItemChecked(inti, True)
                        ElseIf abcd.GetItemCheckState(inti) = CheckState.Unchecked Then
                            CheckedListBox1.SetItemChecked(inti, False)
                        End If
                    Next
                End If
            End If
        End If
        
    End Sub

    Private Sub DataGridView1_RowLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
        intleaverowindex = DataGridView1.CurrentRow.Index
        For inti = 0 To CheckedListBox1.Items.Count - 1

            If CheckedListBox1.GetItemCheckState(inti) = CheckState.Checked Then
                abcd.SetItemChecked(inti, True)
            ElseIf CheckedListBox1.GetItemCheckState(inti) = CheckState.Unchecked Then
                abcd.SetItemChecked(inti, False)

            End If
        Next
        gboolalready = True



    End Sub

    Private Sub DataGridView1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles DataGridView1.Scroll

    End Sub
    Public Sub dsClear(ByVal ds As DataSet, ByVal tblName As String)
        Try
            If ds.Tables.Contains(tblName) Then
                ds.Tables(tblName).Clear()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Dim checked As Boolean
    Dim str1 As String



    Private Sub CheckedListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckedListBox1.SelectedIndexChanged

        For inti = 0 To CheckedListBox1.Items.Count - 1

            If CheckedListBox1.GetItemCheckState(inti) = CheckState.Checked Then
                abcd.SetItemChecked(inti, True)
            ElseIf CheckedListBox1.GetItemCheckState(inti) = CheckState.Unchecked Then
                abcd.SetItemChecked(inti, False)

            End If
        Next
        gboolalready = True

    End Sub  

End Class
Posted
Updated 11-May-12 2:45am
v2

1 solution

Your CheckedListBox and DataGridView are "connected" together by using some trick...
Inside the body of DataGridView1_RowLeave and CheckedListBox1_SelectedIndexChanged you call the same part of code:
VB
...
If CheckedListBox1.GetItemCheckState(inti) = CheckState.Checked Then
                (DataGridView)abcd.SetItemChecked(inti, True)
...

If you use the same part of code more then 1 times, write custom function!

So... if you move row from DataGridView (to nowhere?), you should not be surprise, because the DataGridView count of rows differ of CheckedListBox count of items. To prevent this situation, the count of items in both controls must be equal.

Read more about: CheckedItems collection for CheckedListBox[^]

By the way, your code:
VB
If CheckedListBox1.GetItemCheckState(inti) = CheckState.Checked Then
    abcd.SetItemChecked(inti, True)
ElseIf CheckedListBox1.GetItemCheckState(inti) = CheckState.Unchecked Then
    abcd.SetItemChecked(inti, False)
End If

is not optimal! Take a look at simple trick:
VB
Dim bChecked AS Boolean = TRUE
....
bChecked = (CheckedListBox1.GetItemCheckState(inti) = CheckState.Checked)
abcd.SetItemChecked(inti, bChecked)


Sorry for my language...
   
Comments
ParkashKaur 12-May-12 1:26am
   
this is my code to create custom control.
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
'using System.Linq;
Imports System.Text
Imports System.Windows.Forms
Imports System.Collections
Imports System.Collections.ObjectModel

Namespace WindowsApplication27
Partial Public Class CheckedListBoxColumn
Inherits DataGridViewColumn
Public Sub New()
MyBase.New(New CheckedListBoxCell())
End Sub
Public Overrides Property CellTemplate() As DataGridViewCell
Get
Return MyBase.CellTemplate
End Get
Set(ByVal value As DataGridViewCell)
If value IsNot Nothing AndAlso Not value.[GetType]().IsAssignableFrom(GetType(CheckedListBoxCell)) Then
Throw New InvalidCastException("Must be a CheckedListBoxCell")
End If
MyBase.CellTemplate = value
End Set
End Property
Friend Sub show()
Throw New NotImplementedException()
End Sub

Private Sub checkedListBoxEditingControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
' checkedListBoxEditingControl1.Items.Add("fs");
End Sub
End Class
Public Class CheckedListBoxCell
Inherits DataGridViewCell
Public Sub New()
MyBase.New()
End Sub
Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, ByVal initialFormattedValue As Object, ByVal dataGridViewCellStyle As DataGridViewCellStyle)
' Set the value of the editing control to the current cell value.
MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle)
Dim ctl As CheckedListBoxEditingControl = TryCast(DataGridView.EditingControl, CheckedListBoxEditingControl)
InitializeCheckedListBox(ctl, DirectCast(Me.FormattedValue, ICollection))
End Sub
Private Sub InitializeCheckedListBox(ByVal ctrl As CheckedListBox, ByVal value As ICollection)

ctrl.Items.Clear()
For Each obj As Object In value
' ctrl.Items.Add("fd");
ctrl.Items.Add(obj.ToString())
Next
ctrl.Tag = Me.Value
End Sub
Public Overrides ReadOnly Property EditType() As Type
Get
Return GetType(CheckedListBoxEditingControl)
End Get
End Property
Protected Overrides Function GetFormattedValue(ByVal value As Object, ByVal rowIndex As Integer, ByRef cellStyle As DataGridViewCellStyle, ByVal valueTypeConverter As System.ComponentModel.TypeConverter, ByVal formattedValueTypeConverter As System.ComponentModel.TypeConverter, ByVal context As DataGridViewDataErrorContexts) As Object


If value Is Nothing Then
Return New List(Of Object)()
End If
Return MyBase.GetFormattedValue(value, rowIndex, cellStyle, valueTypeConverter, formattedValueTypeConverter, context)
End Function
Public Overrides ReadOnly Property FormattedValueType() As Type
Get
Return GetType(ICollection)
End Get
End Property
Public Overrides Property ValueType() As Type
Get
Return GetType(ICollection)
End Get
Set(ByVal value As Type)

End Set
End Property
Private internalControl As CheckedListBox
Protected Overrides Sub Paint(ByVal graphics As System.Drawing.Graphics, ByVal clipBounds As System.Drawing.Rectangle, ByVal cellBounds As System.Drawing.Rectangle, ByVal rowIndex As Integer, ByVal cellState As DataGridViewElementStates, ByVal value As Object, _
ByVal formattedValue As Object, ByVal errorText As String, ByVal cellStyle As DataGridViewCellStyle, ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, ByVal
Maciej Los 12-May-12 6:02am
   
... and the comment is?
Sandeep Mewara 12-May-12 5:52am
   
Worth a 5!
Maciej Los 12-May-12 6:02am
   
Thank you ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900