Sunday, October 6, 2013

DatagridView Tutorial with DataGridViewCheckBoxColumn

DatagridView Tutorial with DataGridViewCheckBoxColumn

The best way to set a Yes No entry inside a DataGridView is the use of a DataGridViewCheckBoxColumn. The user could activate or disable a value by checking it.




Lesson 6: Using DataGridViewCheckBoxColumn

From the Visual Basic form Designer, simple add a column and make sure you choose the DataGridViewCheckBoxColumn type. Named your column like cActivate and give a good description like ACTIVATE.

Because the checkbox is no ordinary cell, I have to detect it.
The easiest way is by getting the column index. Here is a very short example and I highlighted the important part. Using a regular if condition, if the column index from the CellMouseClick is the same number of the cActivate index, then we got our DataGridViewCheckBoxColumn object.

I use the previous sample project to make this example. Please not that there is no VALUE or property to get the cell value. You need to use EditedFormattedValue or EditingCellFormattedValue. In this case and in most case, is exactly the same thing.

Download the sample project

All the functions and the step use in this post are inside the sample project. Fell free to take a look at it. When you start the sample project, an initial DataGridView will be filled with random numbers. A save function is called if you close the WinForm.
When you click on a button inside the DataGridView, you will notice it will change color to yellow.



    Private Sub DataGridView1_CellMouseClick(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then
            Me.Text = ("[" & e.RowIndex & " ; " & e.ColumnIndex & "]")
            Dim pt As Point = MousePosition
            ContextMenuStrip1.Show(pt)
        ElseIf e.Button = Windows.Forms.MouseButtons.Left Then
            Dim dgvbc As DataGridViewButtonCell
            Dim dgvbcb As DataGridViewCheckBoxCell
            If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then
                If e.ColumnIndex = cButton.Index Then
                    dgvbc = Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
                    dgvbc.FlatStyle = FlatStyle.Flat
                    dgvbc.Style.BackColor = Color.Yellow
                    dgvbc.Selected = False
                ElseIf e.ColumnIndex = cActivate.Index Then
                    dgvbcb = Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
                    MsgBox(dgvbcb.EditedFormattedValue)
                End If
            End If
        End If
    End Sub

1 comment: