In DataGridView using the CellMouseDoubleClick and detecting when someone clicked the Header
In my DataGridView control, I'd like the user to double click a row and fetch relevant information.
Here is my code: (EDIT)
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex != -1)
{
int studentID = Convert.ToInt32(dataGridView1[0, e.RowIndex].Value);
StudentInformation addForm = new StudentInformation(studentID);
addForm.ShowDialog();
} 开发者_C百科
}
The problem is when someone double clicks the header (and I only found this bug by accident!) an exception fires. I don't want handle anything when the users double clicks the header.
How can I detect when the header has been clicked?
Thank you!
EDIT It seems that header have a RowIndex of -1. Is this the best way to check, or is this a dirty hack?
Check if the datagridview.SelectedRows.Count > 0, this will help you also when no rows are selected
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0 && dataGridView.SelectedRows.Count>0)
{
int studentID = Convert.ToInt32(dataGridView1[0, e.RowIndex].Value);
StudentInformation addForm = new StudentInformation(studentID);
addForm.ShowDialog();
}
}
private void dgvDataGridView_DoubleClick(object sender, EventArgs e)
{
if (sender != null && e != null && ((MouseEventArgs)e).Y <= ((DataGridView)sender).Rows[0].Height)
return; //Double click on Header
private void radgvAreaAdmin_CellDoubleClick(object sender, GridViewCellEventArgs e)
{
if (e.Row.Index <= -1)
//Do your code inside in it.
}
e.rowindex may vary with your focus. But if you use e.row.index, it would always be -1 when we click on Column header of grid. If you want to ignore the double click in header, just use 'return' after the if-condition.
精彩评论