Results 1 to 17 of 17

Thread: DGV CheckBox

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    DGV CheckBox

    Hi

    I have code which saves DGV contents including check box columns as a comma separated text file. I also have correct code which will take the text file and re-insert it into the DGV at a later time. This all works.

    When I'm working on the DGV, I have this code:


    Code:
     Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
    
    If DataGridView1.Columns(e.ColumnIndex).Name = "Column12" Then
                Dim clrscript As Color
                If DataGridView1.Rows(e.RowIndex).Cells("Column12").Value = True Then
                    clrscript = Color.DarkRed
                    DataGridView1.Rows(e.RowIndex).Cells("Column1").Style.BackColor = Color.FromArgb(183, 0, 0)
                    DataGridView1.Rows(e.RowIndex).Cells("Column3").Style.BackColor = Color.FromArgb(183, 0, 0)
    
                ElseIf DataGridView1.Rows(e.RowIndex).Cells("Column12").Value = False Then
                    DataGridView1.Rows(e.RowIndex).Cells("Column1").Style.BackColor = Color.FromArgb(255, 192, 0)
                    DataGridView1.Rows(e.RowIndex).Cells("Column3").Style.BackColor = Color.FromArgb(255, 192, 0)
    
                End If
    
            End If
    
    End Sub
    So that when the check box is true, columns 1 and 3 turn different colours, and when false, go to a yellow colour.

    However, when I "re-insert" my DGV info from my text file, the check boxes come back correctly - as true and false on the right rows - but columns 1 and 3 don't change colour. I've tried a "DataGridView1.Refresh" option but not getting it to work.

    The DGV is unbound. I need it to recognise which check boxes are true and update automatically when the information is opened from a text file.

    Thanks for your help

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: DGV CheckBox

    to force the DataGridView1_CellValueChanged event to fire, use:

    vb Code:
    1. DataGridView1.EndEdit()

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV CheckBox

    Hi .paul

    Thanks for your reply. I've added this to a separate button just to try it out but unfortunately it's not working...

  4. #4
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: DGV CheckBox

    as you add the information from the text file, call endedit (row by row, or just when you change cells("Column12"), depending on how you're loading your dgv) + it'll run DataGridView1_CellValueChanged

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV CheckBox

    Hi Paul..I think my eyes are getting tired this evening or something but I'm not sure where to place the end edit code...this is my code for loading the dgv

    Code:
            If Not DataGridView1.LoadTextFile(tbROLoadMix.Text, ErrorList) Then
                Dim sb As New System.Text.StringBuilder
                sb.AppendLine("Failed to load text file, see error messages below.")
                For Each item In ErrorList
                    sb.AppendLine(item)
                Next
    
                MessageBox.Show(sb.ToString)
            End If

  6. #6
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: DGV CheckBox

    i need to see the actual code that reads the csv + puts it in the dgv to advise you how to do it

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV CheckBox

    Apologies! My mistake...hope this helps


    Code:
    Imports Microsoft.VisualBasic.FileIO
    Module Module1
        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function LoadTextFile( _
          ByVal sender As DataGridView, _
          ByVal FileName As String, _
          ByRef Errors As List(Of String)) As Boolean
    
            If Not IO.File.Exists(FileName) Then
                Errors.Add("Failed to locate '" & FileName & "'")
                Return False
            End If
    
            If sender.ColumnCount <> 16 Then
    
                Errors.Add("Must have three columns to load your text file., there are " & _
                           sender.ColumnCount.ToString & " columns presently.")
    
                Return False
    
            End If
    
            Using MyReader As New TextFieldParser(FileName)
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.Delimiters = New String() {","}
                Dim Line As String()
    
                sender.SuspendLayout()
    
                Try
                    While Not MyReader.EndOfData
                        Try
                            Line = MyReader.ReadFields()
                            '
                            ' For every column per line
                            ' there must be a column in the DataGridView
                            '
                            sender.Rows.Add(New Object() {Line(0), Line(1), Line(2), Line(3), Line(4), Line(5), Line(6), Line(7), Line(8), Line(9), Line(10), Line(11), Line(12), Line(13), Line(14), Line(15)})
                            ' Line(4), Line(5), Line(6), Line(7), Line(8), Line(9), Line(10), Line(11), Line(12), Line(13), Line(14), Line(15), Line(16)})
                        Catch ex As FileIO.MalformedLineException
                            '
                            ' Report problem
                            '
                            Errors.Add(ex.Message)
                        Catch ex As Exception
                            Errors.Add(ex.Message)
                        End Try
                    End While
                Finally
                    sender.ResumeLayout()
                End Try
            End Using
    
            Return Errors.Count = 0
    
        End Function
        
    End Module

  8. #8
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: DGV CheckBox

    vb Code:
    1. Imports Microsoft.VisualBasic.FileIO
    2. Module Module1
    3.     <System.Diagnostics.DebuggerStepThrough()> _
    4.     <System.Runtime.CompilerServices.Extension()> _
    5.     Public Function LoadTextFile( _
    6.       ByVal sender As DataGridView, _
    7.       ByVal FileName As String, _
    8.       ByRef Errors As List(Of String)) As Boolean
    9.  
    10.         If Not IO.File.Exists(FileName) Then
    11.             Errors.Add("Failed to locate '" & FileName & "'")
    12.             Return False
    13.         End If
    14.  
    15.         If sender.ColumnCount <> 16 Then
    16.  
    17.             Errors.Add("Must have three columns to load your text file., there are " & _
    18.                        sender.ColumnCount.ToString & " columns presently.")
    19.  
    20.             Return False
    21.  
    22.         End If
    23.  
    24.         Using MyReader As New TextFieldParser(FileName)
    25.             MyReader.TextFieldType = FileIO.FieldType.Delimited
    26.             MyReader.Delimiters = New String() {","}
    27.             Dim Line As String()
    28.  
    29.             sender.SuspendLayout()
    30.  
    31.             Try
    32.                 While Not MyReader.EndOfData
    33.                     Try
    34.                         Line = MyReader.ReadFields()
    35.                         '
    36.                         ' For every column per line
    37.                         ' there must be a column in the DataGridView
    38.                         '
    39.                         sender.Rows.Add(New Object() {Line(0), Line(1), Line(2), Line(3), Line(4), Line(5), Line(6), Line(7), Line(8), Line(9), Line(10), cbool(Line(11)), Line(12), Line(13), Line(14), Line(15)})
    40.                         sender.endedit
    41.                         ' Line(4), Line(5), Line(6), Line(7), Line(8), Line(9), Line(10), Line(11), Line(12), Line(13), Line(14), Line(15), Line(16)})
    42.                     Catch ex As FileIO.MalformedLineException
    43.                         '
    44.                         ' Report problem
    45.                         '
    46.                         Errors.Add(ex.Message)
    47.                     Catch ex As Exception
    48.                         Errors.Add(ex.Message)
    49.                     End Try
    50.                 End While
    51.             Finally
    52.                 sender.ResumeLayout()
    53.             End Try
    54.         End Using
    55.  
    56.         Return Errors.Count = 0
    57.  
    58.     End Function
    59.    
    60. End Module

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV CheckBox

    Where about should the "end edit" be placed in the above?

  10. #10
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: DGV CheckBox

    it's in there after the row add. i edited it. try it

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV CheckBox

    never spotted that...given it a try but not change to the dgv

  12. #12
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: DGV CheckBox

    try turning Option Strict on. you probably have datatype errors.
    other than you uploading the project + me debugging it for you there's nothing more i can tell you.
    i tested the endedit method before post #2, so i know it should work.

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

    Re: DGV CheckBox

    Greetings, first off have you considered turning Option Strict On ? In the end this will assist when there are problems in your code i.e.

    The following is comparing an object to a Boolean
    Code:
    If DataGridView1.Rows(e.RowIndex).Cells("Column12").Value = True Then
    In regards to your color logic. DataGridView.CellValueChanged Event (under remarks)



    In the case of check box cells, however, you will typically want to handle the change immediately. To commit the change when the cell is clicked, you must handle the DataGridView.CurrentCellDirtyStateChanged event. In the handler, if the current cell is a check box cell, call the DataGridView.CommitEdit method and pass in the Commit value.


    Example, Column1 is a CheckBox and Column2 TextBox
    Code:
    Public Class Form1
        Private Sub Form1_Load(
            ByVal sender As System.Object,
            ByVal e As System.EventArgs) _
        Handles MyBase.Load
    
            DataGridView1.Rows.Add(New Object() {True, "AAA"})
            DataGridView1.Rows.Add(New Object() {True, "BBB"})
            DataGridView1.Rows.Add(New Object() {False, "CCC"})
            DataGridView1.Rows.Add(New Object() {True, "DDD"})
    
        End Sub
        Private Sub DataGridView1SelectAll_CurrentCellDirtyStateChanged(
            ByVal sender As Object,
            ByVal e As EventArgs) _
        Handles DataGridView1.CurrentCellDirtyStateChanged
    
            If TypeOf DataGridView1.CurrentCell Is DataGridViewCheckBoxCell Then
                DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
            End If
    
        End Sub
        Private Sub DataGridView1_CellValueChanged(
            ByVal sender As Object,
            ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
        Handles DataGridView1.CellValueChanged
    
            If DataGridView1.Columns(e.ColumnIndex).Name = "Column1" Then
                If CBool(DataGridView1.Rows(e.RowIndex).Cells("Column1").Value) Then
                    DataGridView1.Rows(e.RowIndex).Cells("Column2").Style.BackColor = Color.Red
                Else
                    DataGridView1.Rows(e.RowIndex).Cells("Column2").Style.BackColor = Nothing
                End If
            End If
    
        End Sub
    End Class

  14. #14

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV CheckBox

    Hi Kevin

    Thanks for your message. I've copied your code into a new project just to see how it works etc, but unfortunately this doesn't have the desired effect. When the form loads, the checkboxes have the correct value but the relevant cells are not coloured.

    I've tried the option strict on your and Paul's advice but not getting anywhere unfortunately :S

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

    Re: DGV CheckBox

    Quote Originally Posted by MacShand View Post
    Hi Kevin

    Thanks for your message. I've copied your code into a new project just to see how it works etc, but unfortunately this doesn't have the desired effect. When the form loads, the checkboxes have the correct value but the relevant cells are not coloured.

    I've tried the option strict on your and Paul's advice but not getting anywhere unfortunately :S
    This is because CellValueChanged has no reason to be called thus no color change. This is where we need CellFormatting event i.e.

    Code:
    Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
        If DataGridView1.Columns(e.ColumnIndex).Name = "Column1" Then
            If e.Value IsNot Nothing Then
                If CBool(e.Value) Then
                    DataGridView1.Rows(e.RowIndex).Cells("Column2").Style.BackColor = Color.Red
                Else
                    DataGridView1.Rows(e.RowIndex).Cells("Column2").Style.BackColor = Nothing
                End If
            End If
        End If
    End Sub
    Lesson to be learned here is rather than use code examine and understand it. In this case this is why I put links in to read before and here.
    DataGridView.CellFormatting Event

  16. #16

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV CheckBox

    Awesome Kevin, thanks for your assistance!

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

    Re: DGV CheckBox

    Quote Originally Posted by MacShand View Post
    Awesome Kevin, thanks for your assistance!
    Your welcome.

Tags for this Thread

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