DataGridViewButton click event
-
I was searching thru the web and couldn't realy find a conclusive explanation on how to attach an event to DataGridViewButton. Since I found the answer to my question I have decided to share it with others... You can not attach an event to a specific DataGridViewButton. The only way to by pass this block is to use the CellClick event of the DataGridView control. By doing so, keep in mind that this event is automaticly attached to any button on the DataGridView. In order to use this event for a specific button on the row, you will need to check if the object which fired the event has the name of your desired button. Take a look at the example:
if (MyGridView.Rows[e.RowIndex].Cell[e.ColumnIndex].Name == "MyButtonName")
{
//do what ever
}Also, if you notice, when you click on any row on the first cloumn (the blank one that cause a full row selection) it fires the same event. The problem is that it sends a column index of -1 which can not retrive a coulmn name. This cause an expectaion error. In order to fix it use this example:
if (
e.ColumnIndex != -1 &&
MyGridView.Rows[e.RowIndex].Cell[e.ColumnIndex].Name == "MyButtonName")
{
//do what ever
}Make sure the first condition is the "e.ColumnIndex != -1". Hope I could help anyone with this information.