Results 1 to 13 of 13

Thread: [RESOLVED] DataGridView CheckBox

  1. #1

    Thread Starter
    Lively Member anamada's Avatar
    Join Date
    Jun 2011
    Location
    Philippines, Makati
    Posts
    107

    Resolved [RESOLVED] DataGridView CheckBox

    Good day everyone!


    I need urgent help on my program.
    In DGV, I have 2 checkbox columns. Column1 and Column 2. Once I checked a checkbox in a column and it happens that there is already a checked checkbox in the other column and they are in the same ROW. It will automatically disable/uncheck the Checked Checkbox.. Meaning only One CheckBox must be allowed to be marked if happens that they are in the same row.

    I'll attach a sample pic of what I wanted to happen.

    This is what i've done so far.

    Code:
    Imports System.Data.SqlClient
    Imports System.Text.RegularExpressions
    Imports System.IO
    Imports System.Net.Mail
    Imports System.Net
    Imports System.Text
    
    Public Class Form1
        Inherits System.Windows.Forms.Form
    
        Dim sql_command As SqlCommand
        Dim connectionString As String
        Dim sql_connection As SqlConnection
        Dim icount As Integer
        Dim datareadersql As SqlDataReader
        Dim sqlstring As String
        Dim str As String
        Dim sqlcom As String
    
        Dim itemlist As New ArrayList()
        Dim value As String
        Dim stoid As String
    
        
        'STOCKHOLDER INFORMATION: Search GO BUTTON
        '
        Private Sub Go1B_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Go1B.Click
            Try
                connectionString = ""
                sql_connection = New SqlConnection(connectionString)
                sql_connection.Open()
    
                If (cSearch1.Text = "" Or tSearch1.Text = "") Then
                    sqlstring = "SELECT STK_HOLD_CODE, STK_HOLD_NAME, STK_FRACTIONAL_SHARES FROM Stkmast WHERE STK_HOLD_NAME LIKE '%" & tSearch1.Text & "%'"
    
                ElseIf cSearch1.SelectedIndex = 0 Then
                    sqlstring = "SELECT STK_HOLD_CODE, STK_HOLD_NAME, STK_FRACTIONAL_SHARES FROM Stkmast WHERE STK_HOLD_NAME LIKE '%" & tSearch1.Text & "%'"
    
                ElseIf cSearch1.SelectedIndex = 1 Then
                    sqlstring = "SELECT STK_HOLD_CODE, STK_HOLD_NAME, STK_FRACTIONAL_SHARES FROM Stkmast WHERE STK_HOLD_CODE LIKE '%" & tSearch1.Text & "%'"
    
                Else
                    MsgBox("Select a Search Criteria")
                End If
    
                sql_command = New SqlCommand(sqlstring, sql_connection)
                Dim sqladapter As New SqlDataAdapter(sql_command)
                Dim stock_info As New DataSet()
                sqladapter.Fill(stock_info, "Stkmast")
                DataGridView1.DataSource = stock_info.Tables("Stkmast")
    
    
                DataGridView1.Columns(0).HeaderText = "Parent"
                DataGridView1.Columns(1).HeaderText = "Child"
                DataGridView1.Columns(2).HeaderText = "Stockholder Code"
                DataGridView1.Columns(3).HeaderText = "Name"
                DataGridView1.Columns(4).HeaderText = "No. of Shares"
    
            Catch ex As Exception
            End Try
        End Sub
        '
        'STOCKHOLDER INFORMATION: DB DATA LOAD
        '
        Private Sub stockInfoGb_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
            connectionString = ""
            sql_connection = New SqlConnection(connectionString)
            sql_connection.Open()
            sqlstring = "SELECT STK_HOLD_CODE, STK_HOLD_NAME FROM Stkmast"
        End Sub
    
    
        '
        'TESTING (STOCKHOLDER CODE)
        '
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Try
    
                For Each row As DataGridViewRow In DataGridView1.Rows
                    Dim cell As DataGridViewCheckBoxCell = CType(row.Cells("checkboxchild"), DataGridViewCheckBoxCell)
                    Dim cell2 As DataGridViewCheckBoxCell = CType(row.Cells("checkboxparent"), DataGridViewCheckBoxCell)
                    If CBool(cell.Value) = True Then
                        stoid = CStr(row.Cells("STK_HOLD_CODE").Value)
                        itemlist.Add(stoid)
                    End If
    
                    If CBool(cell2.Value) = True Then
                        stoid = CStr(row.Cells("STK_HOLD_CODE").Value)
                        itemlist.Add(stoid)
                    End If
    
                Next
                Dim strStrings() As String = CType(itemlist.ToArray(GetType(String)), String())
                Dim strJoinedString As String
    
                For Each astring In itemlist
                    strJoinedString = strJoinedString
                    strJoinedString = Join(strStrings, ",")
    
    
                Next
                MsgBox(strJoinedString)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
            itemlist.Clear()
        End Sub
    
    
        'Private Sub DataGridView1_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown
        '    If e.ColumnIndex = 0 Then
        '        If CBool(DataGridView1(0, e.RowIndex).Value()) = False Then
        '            If MessageBox.Show("Are you sure you want to assign this as a Parent Code?", "CheckBox", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
        '                DataGridView1(0, e.RowIndex).Value = True
    
        '            Else
        '                MessageBox.Show("You are only allowed to choose 1 Parent Code")
        '            End If
        '        End If
        '    End If
        'End Sub
    
    
    
    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
            If (DataGridView1.Columns(e.ColumnIndex).Name = "checkboxparent") Then
                If (e.RowIndex >= 0) Then
    
                    For Each row As DataGridViewRow In Me.DataGridView1.Rows
                        If (row.Index <> e.RowIndex) Then
                            row.Cells("checkboxparent").Value = False
                        End If
                    Next
    
                End If
            End If
    
        End Sub
    
    End Class
    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    If (DataGridView1.Columns(e.ColumnIndex).Name = "checkboxparent") Then
    If (e.RowIndex >= 0) Then

    For Each row As DataGridViewRow In Me.DataGridView1.Rows
    If (row.Index <> e.RowIndex) Then
    row.Cells("checkboxparent").Value = False
    End If
    Next

    End If
    End If

    End Sub
    Attached Images Attached Images   
    Last edited by anamada; Jan 14th, 2012 at 01:10 AM.

  2. #2
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: DataGridView CheckBox

    Look at CellValueChanged event of the DataGridView, check the value of the cells, something like the following

    Code:
    If e.ColumnIndex = DataGridView1.Columns("Check1").Index OrElse e.ColumnIndex = DataGridView1.Columns("Check2").Index Then
        
    End If
    You may also need to work with CurrentCellDirtyStateChanged event i.e.
    Code:
    Private Sub DataGridView1SelectAll_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As EventArgs)
        If TypeOf DataGridView1.CurrentCell Is DataGridViewCheckBoxCell Then
            DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
        End If
    End Sub
    Within the check above you can then determine who was checked/unchecked then look at the other checkbox value to decide your actions as in if the selected checkbox column of the current row is True and the other is True you need to change the value in your underlying datasource for the flip-flop to happen as you are asking for or if the DataGridview is unbound then simply change the value of the opposite checkbox columns value.

    Code:
    If DataGridView1.SelectedColumnName = "Check1" Then
        If DataGridView1.CurrentRowCellValue("Check1") = "True" Then
    
        Else
    
        End If
    End If
    Place the following in a code module
    Code:
    <System.Diagnostics.DebuggerStepThrough()> _
    <Runtime.CompilerServices.Extension()> _
    Function CurrentRowCellValue(ByVal sender As DataGridView, ByVal ColumnName As String) As String
        Dim Result As String = ""
    
        If Not sender.Rows(sender.CurrentRow.Index).Cells(ColumnName).Value Is Nothing Then
            Result = sender.Rows(sender.CurrentRow.Index).Cells(ColumnName).Value.ToString
        End If
    
        Return Result
    
    End Function
    <System.Diagnostics.DebuggerStepThrough()> _
    <Runtime.CompilerServices.Extension()> _
    Function CurrentCellValue(ByVal sender As DataGridView) As DataGridViewCell
        Return sender(sender.SelectedColumnNameIndex, sender.CurrentRow.Index)
    End Function
    <System.Diagnostics.DebuggerStepThrough()> _
    <Runtime.CompilerServices.Extension()> _
    Function SelectedColumnName(ByVal sender As DataGridView) As String
        Return sender.Columns(sender.CurrentCellValue.ColumnIndex).Name
    End Function

  3. #3
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: DataGridView CheckBox

    Some additional possibly useful language extensions for working with CheckBoxColumns

    Code:
    <Runtime.CompilerServices.Extension()> _
    Public Function CheckBoxCount(ByVal GridView As DataGridView, ByVal ColumnIndex As Integer, ByVal Checked As Boolean) As Integer
        Return (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() Where CBool(Rows.Cells(ColumnIndex).Value) = Checked).Count
    End Function
    <Runtime.CompilerServices.Extension()> _
    Public Function CheckBoxCount(ByVal GridView As DataGridView, ByVal ColumnName As String, ByVal Checked As Boolean) As Integer
        Return (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() Where CBool(Rows.Cells(ColumnName).Value) = Checked).Count
    End Function
    <System.Diagnostics.DebuggerStepThrough()> _
    <Runtime.CompilerServices.Extension()> _
    Public Function GetChecked(ByVal GridView As DataGridView, ByVal ColumnName As String) As List(Of DataGridViewRow)
        Return (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() _
                    Where CBool(Rows.Cells(ColumnName).Value) = True).ToList
    End Function

  4. #4

    Thread Starter
    Lively Member anamada's Avatar
    Join Date
    Jun 2011
    Location
    Philippines, Makati
    Posts
    107

    Re: DataGridView CheckBox

    Kevin,

    Man. Thanks to your reply. Working on it

  5. #5

    Thread Starter
    Lively Member anamada's Avatar
    Join Date
    Jun 2011
    Location
    Philippines, Makati
    Posts
    107

    Re: DataGridView CheckBox

    Kevin,

    It's not working this is my code:

    Code:
    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
            If (DataGridView1.Columns(e.ColumnIndex).Name = "checkboxparent") Then
                If (e.RowIndex >= 0) Then
    
                    For Each row As DataGridViewRow In Me.DataGridView1.Rows
                        If (row.Index <> e.RowIndex) Then
                            row.Cells("checkboxparent").Value = False
                        End If
                    Next
                End If
            End If
        End Sub
    
        Private Sub DataGridView1_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged, DataGridView1.CellContentClick
            If e.ColumnIndex = DataGridView1.Columns("checkboxparent").Index OrElse e.ColumnIndex = DataGridView1.Columns("checkboxchild").Index Then
                If DataGridView1.SelectedColumnName = "checkboxparent" Then
                    If DataGridView1.CurrentRowCellValue("checkboxparent") = "True" Then
                        For Each row As DataGridViewRow In Me.DataGridView1.Rows
                            If (row.Index <> e.RowIndex) Then
                                row.Cells("checkboxchild").Value = False
                            End If
                        Next
                    End If
                End If
            End If
        End Sub
    
        Private Sub DataGridView1SelectAll_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As EventArgs)
            If TypeOf DataGridView1.CurrentCell Is DataGridViewCheckBoxCell Then
                DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
            End If
        End Sub

    and at the Module:

    I got this error

    Error 3 Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement. C:\Visual Studio 2010\Projects\ConSo\ConSo\Module1.vb 19 46 ConSo
    Error 2 'SelectedColumnNameIndex' is not a member of 'System.Windows.Forms.DataGridView'. C:\Visual Studio 2010\Projects\ConSo\ConSo\Module1.vb 17 23 ConSo
    Here:

    <System.Diagnostics.DebuggerStepThrough()> _
    <Runtime.CompilerServices.Extension()> _
    Function CurrentCellValue(ByVal sender As DataGridView) As DataGridViewCell
    Return sender(sender.SelectedColumnNameIndex, sender.CurrentRow.Index)
    End Function

  6. #6
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: DataGridView CheckBox

    Quote Originally Posted by anamada View Post
    Kevin,

    It's not working this is my code:

    Code:
    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
            If (DataGridView1.Columns(e.ColumnIndex).Name = "checkboxparent") Then
                If (e.RowIndex >= 0) Then
    
                    For Each row As DataGridViewRow In Me.DataGridView1.Rows
                        If (row.Index <> e.RowIndex) Then
                            row.Cells("checkboxparent").Value = False
                        End If
                    Next
                End If
            End If
        End Sub
    
        Private Sub DataGridView1_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged, DataGridView1.CellContentClick
            If e.ColumnIndex = DataGridView1.Columns("checkboxparent").Index OrElse e.ColumnIndex = DataGridView1.Columns("checkboxchild").Index Then
                If DataGridView1.SelectedColumnName = "checkboxparent" Then
                    If DataGridView1.CurrentRowCellValue("checkboxparent") = "True" Then
                        For Each row As DataGridViewRow In Me.DataGridView1.Rows
                            If (row.Index <> e.RowIndex) Then
                                row.Cells("checkboxchild").Value = False
                            End If
                        Next
                    End If
                End If
            End If
        End Sub
    
        Private Sub DataGridView1SelectAll_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As EventArgs)
            If TypeOf DataGridView1.CurrentCell Is DataGridViewCheckBoxCell Then
                DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
            End If
        End Sub

    and at the Module:

    I got this error





    Here:
    Here is the missing function
    Code:
        <System.Diagnostics.DebuggerStepThrough()> _
        <Runtime.CompilerServices.Extension()> _
        Function SelectedColumnNameIndex(ByVal sender As DataGridView) As Int32
            Return sender.Columns(sender.CurrentCell.ColumnIndex).Index
        End Function

  7. #7
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: DataGridView CheckBox

    I just took a look at your original question

    In DGV, I have 2 checkbox columns. Column1 and Column 2. Once I checked a checkbox in a column and it happens that there is already a checked checkbox in the other column and they are in the same ROW. It will automatically disable/uncheck the Checked Checkbox.. Meaning only One CheckBox must be allowed to be marked if happens that they are in the same row.
    Which I interpret as one row, two checkboxes are to be looked at and not working against multiple rows. If I am not missing anything then why are you using a for statement to look at other column values?

    Working with one row, two checkboxes with a DataTable as the DataSource you can simply use logic similar to below to toggle the same row checkboxes

    bsData is a BindingSource
    Code:
    Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
        If DataGridView1.CurrentRow IsNot Nothing Then
            If e.ColumnIndex = DataGridView1.Columns("Check1").Index OrElse e.ColumnIndex = DataGridView1.Columns("Check2").Index Then
                Dim Row = bsData.CurrentRow
                If DataGridView1.CurrentRowCellValue("Check1") = "True" Then
                    Row.Item("Check2") = False
                Else
                    Row.Item("Check2") = True
                End If
                If DataGridView1.CurrentRowCellValue("Check2") = "True" Then
                    Row.Item("Check1") = False
                Else
                    Row.Item("Check1") = True
                End If
                bsData.DataTable.AcceptChanges()
            End If
        End If
    End Sub

    Language extensions used in addition to those I already provided.
    Code:
    Module BindingSourceExtensions
        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function DataTable(ByVal sender As BindingSource) As DataTable
            If sender.DataSource.GetType.Equals(GetType(System.Data.DataTable)) Then
                Return DirectCast(sender.DataSource, DataTable)
            Else
                Throw New Exception("DataSource is not a DataTable")
            End If
        End Function
    
        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function CurrentRow(ByVal sender As BindingSource) As DataRow
            Return CType((CType(sender.Current, DataRowView)).Row, DataRow)
        End Function
    End Module

  8. #8

    Thread Starter
    Lively Member anamada's Avatar
    Join Date
    Jun 2011
    Location
    Philippines, Makati
    Posts
    107

    Re: DataGridView CheckBox

    Quote Originally Posted by kevininstructor View Post
    I just took a look at your original question



    Which I interpret as one row, two checkboxes are to be looked at and not working against multiple rows. If I am not missing anything then why are you using a for statement to look at other column values?

    Working with one row, two checkboxes with a DataTable as the DataSource you can simply use logic similar to below to toggle the same row checkboxes

    bsData is a BindingSource
    Code:
    Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
        If DataGridView1.CurrentRow IsNot Nothing Then
            If e.ColumnIndex = DataGridView1.Columns("Check1").Index OrElse e.ColumnIndex = DataGridView1.Columns("Check2").Index Then
                Dim Row = bsData.CurrentRow
                If DataGridView1.CurrentRowCellValue("Check1") = "True" Then
                    Row.Item("Check2") = False
                Else
                    Row.Item("Check2") = True
                End If
                If DataGridView1.CurrentRowCellValue("Check2") = "True" Then
                    Row.Item("Check1") = False
                Else
                    Row.Item("Check1") = True
                End If
                bsData.DataTable.AcceptChanges()
            End If
        End If
    End Sub

    Language extensions used in addition to those I already provided.
    Code:
    Module BindingSourceExtensions
        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function DataTable(ByVal sender As BindingSource) As DataTable
            If sender.DataSource.GetType.Equals(GetType(System.Data.DataTable)) Then
                Return DirectCast(sender.DataSource, DataTable)
            Else
                Throw New Exception("DataSource is not a DataTable")
            End If
        End Function
    
        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function CurrentRow(ByVal sender As BindingSource) As DataRow
            Return CType((CType(sender.Current, DataRowView)).Row, DataRow)
        End Function
    End Module

    Kevin,

    I have a question. How to use BindingSource? As far as I know I need to create a data set and connect it to the database? Am I right? Can you give me a quick tutorial. And Kevin. What if my database is attached/connected to MS SQL SERVER 2008 R2? Is there special process that I need to do first?

    Still getting error in
    Code:
    Module Module1
        <System.Diagnostics.DebuggerStepThrough()> _
    <Runtime.CompilerServices.Extension()> _
        Function CurrentRowCellValue(ByVal sender As DataGridView, ByVal ColumnName As String) As String
            Dim Result As String = ""
    
            If Not sender.Rows(sender.CurrentRow.Index).Cells(ColumnName).Value Is Nothing Then
                Result = sender.Rows(sender.CurrentRow.Index).Cells(ColumnName).Value.ToString
            End If
    
            Return Result
    
        End Function
    
        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function DataTable(ByVal sender As BindingSource) As DataTable
            If sender.DataSource.GetType.Equals(GetType(System.Data.DataTable)) Then
                Return DirectCast(sender.DataSource, DataTable)
            Else
                Throw New Exception("DataSource is not a DataTable")
            End If
        End Function
    
        <System.Diagnostics.DebuggerStepThrough()> _
        <Runtime.CompilerServices.Extension()> _
        Function SelectedColumnNameIndex(ByVal sender As DataGridView) As Int32
            Return sender.Columns(sender.CurrentCell.ColumnIndex).Index
        End Function
    
    
        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function CurrentRow(ByVal sender As BindingSource) As DataRow
            Return CType((CType(sender.Current, DataRowView)).Row, DataRow)
        End Function
    
        <System.Diagnostics.DebuggerStepThrough()> _
        <Runtime.CompilerServices.Extension()> _
        Function SelectedColumnName(ByVal sender As DataGridView) As String
            Return sender.Columns(sender.CurrentCellValue.ColumnIndex).Name
        End Function
    
        <Runtime.CompilerServices.Extension()> _
        Public Function CheckBoxCount(ByVal GridView As DataGridView, ByVal ColumnIndex As Integer, ByVal Checked As Boolean) As Integer
            Return (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() Where CBool(Rows.Cells(ColumnIndex).Value) = Checked).Count
        End Function
        <Runtime.CompilerServices.Extension()> _
        Public Function CheckBoxCount(ByVal GridView As DataGridView, ByVal ColumnName As String, ByVal Checked As Boolean) As Integer
            Return (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() Where CBool(Rows.Cells(ColumnName).Value) = Checked).Count
        End Function
        <System.Diagnostics.DebuggerStepThrough()> _
        <Runtime.CompilerServices.Extension()> _
        Public Function GetChecked(ByVal GridView As DataGridView, ByVal ColumnName As String) As List(Of DataGridViewRow)
            Return (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() _
                        Where CBool(Rows.Cells(ColumnName).Value) = True).ToList
        End Function
    End Module

  9. #9
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: DataGridView CheckBox

    First off for your task at hand there is no need for a DataSet, query your database (in this case it sounds like SQL-Server, if the database was IBM-DB2 or MS-Access you still query the database but with a different connection string) and return the results to a DataTable as explained below.

    Focusing on working with data returned from a SELECT statement against a table in a database you load a DataTable with the results from your SELECT statement then assign the DataTable as the DataSource of the BindingSource. At this point you would assign the BindingSource to the say a DataGridView DataSource.

    Given the above, you can inspect and change data viewed in the DataGridView via the BindingSource rather than the DataGridView for one using the Position Changed event of the BindingSource as shown below.

    One of the columns is named notes, to see the value while traversing a DataGridView the following code will do this. Note that a language extension is used which is also overloaded to return either a string value of a column or a DataRow representing the current row in the underlying DataTable.

    Code:
        Private Sub bsData_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles bsData.PositionChanged
            Console.WriteLine("Note value for current row [{0}]", bsData.CurrentRow("Note"))
        End Sub
    Suppose we want the current row
    Code:
    Dim Row = bsData.CurrentRow
    Now we want to change a column named Checked which is type Boolean to False we would use the following

    Code:
    Row.Item("Check2") = False
    Then accept the changes in the DataTable (uses another language extension).

    Code:
    bsData.DataTable.AcceptChanges()
    At this point nothing has been saved back to your database. To do this you would have included in your original SELECT statement the id field so that when updating the data with an update statement your where clause would find the row via the id value obtained from the underlying DataTable which is the source of the BindingSource.

    The above is a start, review the attached VS2008 project which has three columns, two are Boolean and one a string. Changing the value of one CheckBox on a row will toggle the other CheckBox on the same row which is what you wanted. I also show a normal CheckBox bounded to one of the Boolean fields in the underlying DataTable plus showing one method to obtain data in the Position Changed event of the BindingSource.


    One last thing, I favor language extension if you have not already guessed. This is personal perference. Sometimes to create an extension method more code is used than if simply using a function but to me I a) favor methods over functions b) 99.99% of the time I remember method names over functions c) commonality between different types.

    For the last reason I have the exact same method name for two different data providers, again makes things simple.
    Code:
        <System.Diagnostics.DebuggerStepThrough()> _
        <Runtime.CompilerServices.Extension()> _
        Public Function IsOpen(ByVal sender As OleDb.OleDbConnection) As Boolean
            Return sender.State = ConnectionState.Open
        End Function
    Code:
        <System.Diagnostics.DebuggerStepThrough()> _
        <Runtime.CompilerServices.Extension()> _
        Public Function IsOpen(ByVal sender As iDB2Connection) As Boolean
            Return sender.State = ConnectionState.Open
        End Function
    Attached Files Attached Files

  10. #10

    Thread Starter
    Lively Member anamada's Avatar
    Join Date
    Jun 2011
    Location
    Philippines, Makati
    Posts
    107

    Re: DataGridView CheckBox

    Kevin,

    I just did an simple alternate solution and i find it working


    Code:
    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
            If (DataGridView1.Columns(e.ColumnIndex).Name = "checkboxparent") Then
                If (e.RowIndex >= 0) Then
                    Me.DataGridView1.Rows(e.RowIndex).Cells(1).Value = False
                    For Each row As DataGridViewRow In Me.DataGridView1.Rows
                        If (row.Index <> e.RowIndex) Then
                            row.Cells("checkboxparent").Value = False
                        End If
                    Next
                End If
            Else
                If (e.RowIndex >= 0) Then
                    Me.DataGridView1.Rows(e.RowIndex).Cells(0).Value = False
                End If
            End If
    
        End Sub
    Thanks Dude for giving me new ways and ideas. +1 Rep to you
    Last edited by anamada; Aug 2nd, 2011 at 01:50 AM.

  11. #11
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: DataGridView CheckBox

    Quote Originally Posted by anamada View Post
    Kevin,

    I just did an simple alternate solution and i find it working


    Code:
    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
            If (DataGridView1.Columns(e.ColumnIndex).Name = "checkboxparent") Then
                If (e.RowIndex >= 0) Then
                    Me.DataGridView1.Rows(e.RowIndex).Cells(1).Value = False
                    For Each row As DataGridViewRow In Me.DataGridView1.Rows
                        If (row.Index <> e.RowIndex) Then
                            row.Cells("checkboxparent").Value = False
                        End If
                    Next
                End If
            Else
                If (e.RowIndex >= 0) Then
                    Me.DataGridView1.Rows(e.RowIndex).Cells(0).Value = False
                End If
            End If
    
        End Sub
    Thanks Dude for giving me new ways and ideas. +1 Rep to you
    Your welcome. Simple as you call it it is not a good solution though, why go thru all the rows when the row you need is presented. But if you are happy with it than so be it.

  12. #12

    Thread Starter
    Lively Member anamada's Avatar
    Join Date
    Jun 2011
    Location
    Philippines, Makati
    Posts
    107

    Re: [RESOLVED] DataGridView CheckBox

    Kevin,

    My solution would be just for the mean time.

    I need another help.

    Code:
     Try
                For Each row As DataGridViewRow In DataGridView1.Rows
                    Dim cell As DataGridViewCheckBoxCell = CType(row.Cells("checkboxchild"), DataGridViewCheckBoxCell)
                    Dim cell2 As DataGridViewCheckBoxCell = CType(row.Cells("checkboxparent"), DataGridViewCheckBoxCell)
                    If CBool(cell.Value) = True Then
                        stoid = CStr(row.Cells("STK_HOLD_CODE").Value)
                        itemlist.Add(stoid)
                    End If
                    If CBool(cell2.Value) = True Then
                        stoid = CStr(row.Cells("STK_HOLD_CODE").Value)
                        itemlist.Add(stoid)
                    End If
    
                Next
                Dim strStrings() As String = CType(itemlist.ToArray(GetType(String)), String())
                Dim strJoinedString As String = String.Empty
    
                For Each astring In itemlist
                    strJoinedString = strJoinedString
                    strJoinedString = Join(strStrings, ",")
                Next
                MsgBox(strJoinedString)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
            itemlist.Clear()
            
        End Sub
    I want a validation preferably a msgbox.
    There should be a checked Parent and Child. If the chkboxes are empty it will trigger a msgbox to inform the user to choose at least 1 Parent and Child.

    Looking forward on your reply

  13. #13
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: [RESOLVED] DataGridView CheckBox

    Quote Originally Posted by anamada View Post
    Kevin,

    My solution would be just for the mean time.

    I need another help.

    Code:
     Try
                For Each row As DataGridViewRow In DataGridView1.Rows
                    Dim cell As DataGridViewCheckBoxCell = CType(row.Cells("checkboxchild"), DataGridViewCheckBoxCell)
                    Dim cell2 As DataGridViewCheckBoxCell = CType(row.Cells("checkboxparent"), DataGridViewCheckBoxCell)
                    If CBool(cell.Value) = True Then
                        stoid = CStr(row.Cells("STK_HOLD_CODE").Value)
                        itemlist.Add(stoid)
                    End If
                    If CBool(cell2.Value) = True Then
                        stoid = CStr(row.Cells("STK_HOLD_CODE").Value)
                        itemlist.Add(stoid)
                    End If
    
                Next
                Dim strStrings() As String = CType(itemlist.ToArray(GetType(String)), String())
                Dim strJoinedString As String = String.Empty
    
                For Each astring In itemlist
                    strJoinedString = strJoinedString
                    strJoinedString = Join(strStrings, ",")
                Next
                MsgBox(strJoinedString)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
            itemlist.Clear()
            
        End Sub
    I want a validation preferably a msgbox.
    There should be a checked Parent and Child. If the chkboxes are empty it will trigger a msgbox to inform the user to choose at least 1 Parent and Child.

    Looking forward on your reply
    The following writes to the console which of course can go to a MsgBox.
    Code:
    Private Sub cmdValidate_Click( _ 
    	ByVal sender As System.Object, _ 
    	ByVal e As System.EventArgs) _ 
    	Handles cmdValidate.Click
    	
       Dim BothFalseList = _
          ( _
             From Row In DataGridView1.Rows.Cast(Of DataGridViewRow)() _
             Where CBool(Row.Cells("Check1").Value) = False AndAlso _
                   CBool(Row.Cells("Check2").Value) = False _
             Select Index = Row.Index.ToString).ToArray
    
       If BothFalseList.Count > 0 Then
    
          Console.WriteLine("The following rows are invalid{0}{1}", _
                            Environment.NewLine, _
                            String.Join(",", BothFalseList))
    
       End If
    End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width