pikk
pikk

Reputation: 855

datagridview button column Winforms

I have a button column on a DataGridView and I am trying to handle a Button.Click event but nothing happens when I click a button. Any help?

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

Upvotes: 2

Views: 9008

Answers (3)

Vishal.s Anand
Vishal.s Anand

Reputation: 11

Let me get/clarify that you have button on each row of datagridview in c# windows forms. So in order to get button click event of datagridview i show you a sample c# code which worked fine for me! Given below is my c# code of button click event of datagridview which worked fine:

private void dgTasks_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        var button = (DataGridView)sender;
        if (button.Columns[6] is DataGridViewColumn && e.RowIndex >= 0)
        {
       MessageBox.Show("You have clicked Cancel button of a row of datagridview ", "Task", MessageBoxButtons.OK, MessageBoxIcon.Information); 
        }
        }

Where dgTasks is name of my datagridview in c# winforms. button.Columns[6] is column number of my datagridview where i have button column named:btnCancel,header text:CANCEL and text:Cancel. This is just a sample! Hope you find it useful.!

Upvotes: 1

Kev Ritchie
Kev Ritchie

Reputation: 1647

It sounds like your event hasn't registered correctly. To check, from the Designer, highlight the DataGridView control and select Properties, under Events check if the CellClick event has an entry, if not there should be a drop down available that should list your event - select it and this should solve your problem.

Upvotes: 0

dknaack
dknaack

Reputation: 60438

I have tried your sample and it works. Did you really bind the event to your DataGridView ?

Please check the InitializeComponent() Method in your <YourFormName>.Designer.cs class. Did it really has

this.dataGridView1.CellClick += 
  new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);

and you don't remove the handler at another place in code ?

The DataGridViewButtonColumn MSDN page has this to say:

To respond to user button clicks, handle the DataGridView.CellClick or DataGridView.CellContentClick event. In the event handler, you can use the DataGridViewCellEventArgs.ColumnIndex property to determine whether the click occurred in the button column. You can use the DataGridViewCellEventArgs.RowIndex property to determine whether the click occurred in a button cell and not on the column header.

Upvotes: 2

Related Questions