Reputation: 2923
I have a DataGridView which I populate using DataAdapter + DataTable.
I used the following code to create a button:
#region CreatGridButtons
//Botão DELETAR
DataGridViewButtonColumn btn_deletar = new DataGridViewButtonColumn();
btn_deletar.HeaderText = "DELETAR";
btn_deletar.Text = "DELETAR";
btn_deletar.Name = "btn_apagar";
btn_deletar.UseColumnTextForButtonValue = true;
DataGridViewButtonColumn btn_editar = new DataGridViewButtonColumn();
btn_editar.HeaderText = "EDITAR";
btn_editar.Text = "EDITAR";
btn_editar.Name = "btn_editar";
btn_editar.UseColumnTextForButtonValue = true;
dgv_tipo_despesas.Columns.Add(btn_deletar);
dgv_tipo_despesas.Columns.Add(btn_editar);
#endregion
Also, I tried this:
private void dgv_tipo_despesas_CellClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || dgv_tipo_despesas.cell) return;
{
///ExecuteSomeCode
}
}
But it gave me this error: * Object reference not set to an instance of an object.*
I need to execute some code when these buttons are pressed/clicked. I have already accomplished this goal by using the following events:
They both work fine, but... It is also fired when I click on the Column's Header. I'd like an event that only fires when the button is clicked... Is there any?
Upvotes: 0
Views: 1980
Reputation: 2923
I found the solution, I just need to check if it is NOT a DataGridViewButtomColumn and the .RowIndex. Like this:
if (!(MyDataGridView.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex != -1)) return;
{
//MyCodeHere
}
Upvotes: 0
Reputation: 1398
You should be able to use these events but with checking that the e.Source (or something similar) is one of the cells you want to be clickable.
Upvotes: 1
Reputation: 1823
According to MSDN it doesn't look like it since the the header is also a row.
What you can do is to use the DataGridViewCellEventArgs.RowIndex property to determine whether the click occurred in a button cell and not on the column header.
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewbuttoncolumn(v=vs.110).aspx
Upvotes: 1