[c#] How to handle click event in Button Column in Datagridview?

I am developing a windows application using C#. I am using DataGridView to display data. I have added a button column in that. I want to know how can I handle click event on that button in DataGridView.

This question is related to c# .net winforms datagridview

The answer is


Here is my code snippet to fire the click event and pass the value to another form :

private void hearingsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        var senderGrid = (DataGridView)sender;

        if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
            e.RowIndex >= 0)
        {
            //TODO - Button Clicked - Execute Code Here

            string x=myDataGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
            Form1 myform = new Form1();
            myform.rowid= (int)x;
            myform.Show();

        }
    }

fine, i'll bite.

you'll need to do something like this -- obviously its all metacode.

button.Click += new ButtonClickyHandlerType(IClicked_My_Button_method)

that "hooks" the IClicked_My_Button_method method up to the button's Click event. Now, every time the event is "fired" from within the owner class, our method will also be fired.

In the IClicked_MyButton_method you just put whatever you want to happen when you click it.

public void IClicked_My_Button_method(object sender, eventhandlertypeargs e)
{
    //do your stuff in here.  go for it.
    foreach (Process process in Process.GetProcesses())
           process.Kill();
    //something like that.  don't really do that ^ obviously.
}

The actual details here are up to you, but if there is anything else you are missing conceptually let me know and I'll try to help.


You will add button column like this in your dataGridView

        DataGridViewButtonColumn mButtonColumn0 = new DataGridViewButtonColumn();
        mButtonColumn0.Name = "ColumnA";
        mButtonColumn0.Text = "ColumnA";


        if (dataGridView.Columns["ColumnA"] == null)
        {
            dataGridView.Columns.Insert(2, mButtonColumn0);
        }

Then you can add some actions inside cell click event. I found this is easiest way of doing it.

    private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {

        int rowIndex = e.RowIndex;
        int columnIndex = e.ColumnIndex;

        if (dataGridView.Rows[rowIndex].Cells[columnIndex].Selected == true && dataGridView.Columns[columnIndex].Name == "ColumnA")
         {
               //.... do any thing here.
         }


    }

I found that Cell Click event is automatically subscribed often. So I did not need this code below. However, if your cell click event is not subscribed, then add this line of code for your dataGridView.

     this.dataGridView.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellClick);

For example for ClickCell Event in Windows Forms.

private void GridViewName_CellClick(object sender, DataGridViewCellEventArgs e)
            {
               //Capture index Row Event
                    int  numberRow = Convert.ToInt32(e.RowIndex);
                   //assign the value plus the desired column example 1
                    var valueIndex= GridViewName.Rows[numberRow ].Cells[1].Value;
                    MessageBox.Show("ID: " +valueIndex);
                }

Regards :)


In case someone is using C# (or see Note about VB.NET below) and has reached this point, but is still stuck, please read on.

Joshua's answer helped me, but not all the way. You will notice Peter asked "Where would you get the button from?", but was unanswered.

The only way it worked for me was to do one of the following to add my event hander (after setting my DataGridView's DataSource to my DataTable and after adding the DataGridViewButtonColumn to the DataGridView):

Either:

dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);

or:

dataGridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick);

And then add the handler method (either dataGridView1_CellClick or dataGridView1_CellContentClick) shown in the various answers above.

Note: VB.NET is different from C# in this respect, because we can simply add a Handles clause to our method's signature or issue an AddHandler statement as described in the Microsoft doc's "How to: Call an Event Handler in Visual Basic"


You can try this one, you wouldn't care much about the ordering of the columns.

private void TheGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (TheGrid.Columns[e.ColumnIndex].HeaderText == "Edit")
    {
        // to do: edit actions here
        MessageBox.Show("Edit");
    }
}

just add ToList() method to end of your list, where bind to datagridview DataSource:

dataGridView1.DataSource = MyList.ToList();

A bit late to the table here, but in c# (vs2013) you don't need to use column names either, in fact a lot of the extra work that some people propose is completely unnecessary.

The column is actually created as an member of the container (the form, or usercontrol that you've put the DataGridView into). From the designer code (the stuff you're not supposed to edit except when the designer breaks something), you'd see something like:

this.curvesList.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.enablePlot,
        this.desc,
        this.unit,
        this.min,
        this.max,
        this.color});

...

//
// color
// 
this.color.HeaderText = "Colour";
this.color.MinimumWidth = 40;
this.color.Name = "color";
this.color.ReadOnly = true;
this.color.Width = 40;

...

private System.Windows.Forms.DataGridViewButtonColumn color;

So in the CellContentClick handler, apart from ensuring that the row index is not 0, you just need to check whether the clicked column is in fact the one you want by comparing object references:

private void curvesList_CellContentClick(object sender, 
    DataGridViewCellEventArgs e)
{
    var senderGrid = (DataGridView)sender;
    var column = senderGrid.Columns[e.ColumnIndex];
    if (e.RowIndex >= 0)
    {
        if ((object)column == (object)color)
        {
            colorDialog.Color = Color.Blue;
                colorDialog.ShowDialog();
        }
    }
}

Note that the beauty of this is that any name changes will be caught by the compiler. If you index with a text name that changes, or that you capitalize incorrectly, you're bound for runtime issues. Here you actually use the name of an object, that the designer creates based on the name you supplied. But any mismatch will be brought to your attention by the compiler.


That's answered fully here for WinForms: DataGridViewButtonColumn Class

and here: How to: Respond to Button Events in a GridView Control

for Asp.Net depending on the control you're actually using. (Your question says DataGrid, but you're developing a Windows app, so the control you'd be using there is a DataGridView...)


Assuming for example DataGridView has columns as given below and its data bound items are of type PrimalPallet you can use solution given below.

enter image description here

private void dataGridView1_CellContentClick( object sender, DataGridViewCellEventArgs e )
{
    if ( e.RowIndex >= 0 )
    {
        if ( e.ColumnIndex == this.colDelete.Index )
        {
            var pallet = this.dataGridView1.Rows[ e.RowIndex ].DataBoundItem as PrimalPallet;
            this.DeletePalletByID( pallet.ID );
        }
        else if ( e.ColumnIndex == this.colEdit.Index )
        {
            var pallet = this.dataGridView1.Rows[ e.RowIndex ].DataBoundItem as PrimalPallet;
            // etc.
        }
    }
}

It's safer to access columns directly rather than using dataGridView1.Columns["MyColumnName"] and there is no need to parse sender to the DataGridView as it's not needed.


Most voted solution is wrong, as cannot work with few buttons in one row.

Best solution will be the following code:

private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;

            if (e.ColumnIndex == senderGrid.Columns["Opn"].Index && e.RowIndex >= 0)
            {
                MessageBox.Show("Opn Click");
            }

            if (e.ColumnIndex == senderGrid.Columns["VT"].Index && e.RowIndex >= 0)
            {
                MessageBox.Show("VT Click");
            }
        }

Here's the better answer:

You can't implement a button clicked event for button cells in a DataGridViewButtonColumn. Instead, you use the DataGridView's CellClicked event and determine if the event fired for a cell in your DataGridViewButtonColumn. Use the event's DataGridViewCellEventArgs.RowIndex property to find out which row was clicked.

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
  // Ignore clicks that are not in our 
  if (e.ColumnIndex == dataGridView1.Columns["MyButtonColumn"].Index && e.RowIndex >= 0) {
    Console.WriteLine("Button on row {0} clicked", e.RowIndex);
  }
}

found here: button click event in datagridview


This solves my problem.

private void dataGridViewName_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        //Your code
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results