I have a DataGridView and it has 4 columns. I use the event CellClick so that when user clicks on the row, then it will be removed from DataGridView. Everything works fine, but when user by mistake click on the column header(name of the column) then the CellClick event appears and of course program crashes because i'm trying to remove a row and user clicked on the column header. Can I do something with that? Is there any property to disable possibility of clicking on the column header?
0
votes
3 Answers
2
votes
1
votes
You want to check the e.RowIndex property. If it's -1, this will be the header row. See Andy G's post for a code snippet...
Are you sure you want to delete just on a single click of the row? It seems quite dangerous to me, users could very easily click on the wrong row by mistake. It would be better to select the row, and then either have a delete button by way of a menu strip, or by right clicking on the row and having a context menu pop up, which the user could then select a delete option.
0
votes
You need to read the DataGridViewCellEventArgs-object's property RowIndex, which returns -1 if a DataGridViewRow wasn't used in the click. I prefer to make this kind of check in one line, like this:
private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
// If a non-DataGridViewRow was clicked, return
if (e.RowIndex == -1) { return; }
// Your old code here
}