Add Images and Controls to the DataGridView
To create a custom column with the DataGrid, you needed to implement the
functionality yourself by deriving a custom DataGridColumnStyle class that would need
dozens of lines of code. The DataGridView provides a much simpler model. In
fact, you can add new columns right alongside your data-bound
columns!
Note
There's a lot more that you can do with theDataGridView, including adding static buttons and images.
How do I do that?
In many scenarios, it's useful to display a button next to each
row in a grid. Clicking this button can then remove a record, add an
item to a shopping cart, or call up another window with more
information. The DataGridView makes
this easy with the DataGridViewButtonColumn class. You simply
need to create a new instance, specify the button text, and add it to
the end of the grid:
' Create a button column.
Dim Details As New DataGridViewButtonColumn( )
Details.Name = "Details"
' Turn off data-binding and show static text.
' (You could use a property from the table by setting
' the DataPropertyName property instead.)
Details.UseColumnTextForButtonValue = False
Details.Text = "Details..."
' Clear the header.
Details.HeaderText = ""
' Add the column.
DataGridView1.Columns.Insert(DataGridView1.Columns.Count, Details)Once you've performed this easy task, you can intercept the
CellClick event to perform another
action (Figure 3-14 shows
the result of this simple test):
Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access