C# DataGridView Columns - Add Button Column

July 5, 2017 Oclemy C# DataGridView, C# Button 1 minute, 14 seconds

Hello guys.Here is a C# DataGridView Button Column example tutorial.

DataGridView can be used to display several types of data. These different types shall correspond to different DataGridView columns.

DataGridViewButtonColumn

  • To Show buttons in row cells.
  • Obviously is an unbound column.
  • Useful way of providing action buttons to users, e.g. delete, edit etc.
  • Handle Clicks using DataGridView,CellClick events.

Today we see an example involving CheckBox column.To have an overview of DataGridView Columns,see DataGridView Column Types.

Otherwise let's see a Button example below :

using System;
using System.Collections;

using System.Windows.Forms;

namespace Button_Column
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            update();
        }

        //UPDATE DGVIEW
        public void update()
        {
            //ADD COLUMNS
            dataGridView1.ColumnCount = 3;
            dataGridView1.Columns[0].Name = "Position";
            dataGridView1.Columns[1].Name = "Team";
            dataGridView1.Columns[2].Name = "Points";

            //ADD ROWS
            ArrayList row = new ArrayList();
            row.Add("1");
            row.Add("Man Utd");
            row.Add("78");
            dataGridView1.Rows.Add(row.ToArray());

            //2ND ROW
            row = new ArrayList();
            row.Add("2");
            row.Add("Man City");
            row.Add("77");
            dataGridView1.Rows.Add(row.ToArray());

            //3rd ROW
            row = new ArrayList();
            row.Add("3");
            row.Add("Chelsea");
            row.Add("74");
            dataGridView1.Rows.Add(row.ToArray());

            ////ADD BUTTON COLUMN
            DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
            btn.HeaderText = "Buttons";
            btn.Name = "button";
            btn.Text = "Click Me";
            btn.UseColumnTextForButtonValue = true;
            dataGridView1.Columns.Add(btn);

        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.ColumnIndex==3)
            {
                MessageBox.Show((e.RowIndex+1).ToString() +" Row Clicked");
            }
        }
    }
}

Reminders

  • Please add a DataGridView to your form.
  • In this case I have called it datagridview1.

Comments