Windows Forms: How to add a Button each row in a DataGridView in C#

This post shows you how to add a button to each row in a DataGridView C# Windows Forms Application.

Opening your Visual Studio, then click New Project.

Next, select Visual C# on the left, then Windows and then select Windows Forms Application, you can enter name your project "AddButtonToDataGridView" and then click OK

c# add button datagridview

c# add button to datagridview cell

Opening your form designer, then drag a DataGridView from the Visual Studio toolbox into your form designer, you can set the DockStyle property of the DataGridView to Fill.

c# datagridview

Creating a Customer class allows you to store data

public class Customers
{
    public string CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
}

Adding a Form_Load event handler that allows you to initialize data, then add data to BindingSource.

private void Form1_Load(object sender, EventArgs e)
{
    //Init data
    customersBindingSource.Add(new Customers() { CustomerID = "1", CustomerName = "Maria Anders", Email = "maria@gmail.com", Address = "Obere Str. 57" });
    customersBindingSource.Add(new Customers() { CustomerID = "2", CustomerName = "Ana Trujillo", Email = "ana171@gmail.com", Address = "Avada. de la Cons" });
    customersBindingSource.Add(new Customers() { CustomerID = "3", CustomerName = "Thomas Hardy", Email = "thomad@gmail.com", Address = "120 Hanover Sq." });
    customersBindingSource.Add(new Customers() { CustomerID = "4", CustomerName = "Elizabeth Liconln", Email = "elizabeth@gmail.com", Address = "23 Tsawassen" });
}

 

How to add edit and delete button in datagridview in c#

c# gridview add row button

Finaly, you can add a CellContentClick event handler to DataGridView that allows you to check the column name you click.

private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    //Check deleted rows
    if (dataGridView.Columns[e.ColumnIndex].Name == "Delete")
    {
        if (MessageBox.Show("Are you sure want to delete this record ?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            customersBindingSource.RemoveCurrent();
    }
}

You can view the video below, to know how to add button to datagridview in c# windows forms application.

VIDEO TUTORIAL