How to determine user has clicked DataGridView but not a Cell
Asked Answered
W

2

8

I want to prompt the user to enter new elements into a databound collection when they click in the empty area of a DataGridView. How can I find out if the user has clicked inside of the DataGridView (the grey area by default), but not in a Column/Row/Cell?

Weese answered 1/8, 2013 at 13:42 Comment(1)
you can check the e.Originalsource property of change eventhandler..Drawl
B
11

You can use MouseClick event and do a hit test for it.

private void dgv_MouseClick(object sender, MouseEventArgs e)
{
    var ht = dgv.HitTest(e.X, e.Y);

    if (ht.Type == DataGridViewHitTestType.None)
    {
         //clicked on grey area
    }
}
Backscratcher answered 1/8, 2013 at 13:49 Comment(0)
M
2

To determine when the user has clicked on a blank part of the DataGridView, you're going to have to handle its MouseUp event.

In that event, you can HitTest the click location and watch for this to indicate HitTestInfo.Nowhere.

For example:

private void myDataGridView_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
    //'#See if the left mouse button was clicked
    if (e.Button == MouseButtons.Left) {
        //'#Check the HitTest information for this click location
        if (myDataGridView.HitTest(e.X, e.Y) == HitTestInfo.Nowhere) {
            // Do what you want
        }
    }
}
Medina answered 1/8, 2013 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.