Adding Button to DataGridView in VB.NET

The DataGridView control is exceptionally versatile and adaptable, showcasing an extensive range of options for customization and enhancement. It boasts a plethora of properties, methods, and events that facilitate the fine-tuning of its visual presentation and functionality. In terms of column types, the DataGridView control offers an impressive selection of TextBox, CheckBox, Image, Button, ComboBox, and Link columns, each tailored to accommodate specific data requirements.

Below is a VB.NET program that demonstrates how to add a button to a cell in a DataGridView control. It also showcases the DataGridView.CellClick event, which identifies the button that the user clicked.

Full Source VB.NET
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim btn As New DataGridViewButtonColumn() DataGridView1.Columns.Add(btn) btn.HeaderText = "Click Data" btn.Text = "Click Here" btn.Name = "btn" btn.UseColumnTextForButtonValue = True End Sub Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick If e.ColumnIndex = 3 Then MsgBox(("Row : " + e.RowIndex.ToString & " Col : ") + e.ColumnIndex.ToString) End If End Sub End Class

Among these options, the DataGridViewButtonColumn stands out, enabling the incorporation of cell buttons within a designated column. This feature allows for the seamless integration of interactive elements within the grid, enhancing the user experience.

Conclusion

By effectively managing the DataGridView.CellClick event, you can effortlessly capture and respond to user interactions with these button cells, effortlessly incorporating dynamic and responsive behavior into your application.