Monday, September 30, 2013

DatagridView Tutorial with DataGridViewButtonCell

DatagridView Tutorial with DataGridViewButtonCell

I have shown you how to quickly learn to use a DataGridView. How to insert? How to delete? How to do basic operation?  In that first post, you used the DataGridViewTextBoxColumn.  Reading that tutorial is like making a MS-Access or a MS-Excel. Now is time to enhance a little bit your DataGridView using button inside you table. Again, there is nothing to hard to start with.

Lesson 5: Using DataGridViewButtonCell

From the Visual Basic form Designer, simple add a column and make sure you choose the DataGridViewButtonCell type. Named your column like cButton and give a good description like BUTTON.
Because the Button cell 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 cButton index, then we got our DataGridViewButtonCell object.
My example above simple change the color of the button after a click, change the style and deselect the button object. Fell freer to do some general testing.

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
        ElseIf e.Button = Windows.Forms.MouseButtons.Left Then
            Dim dgvbc As DataGridViewButtonCell
            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
                End If
            End If
        End If
    End Sub


Previous post : DatagridView Tutorial

No comments:

Post a Comment