views:

841

answers:

2

I want to override the behavior of a mouse click in the DataGridView header/column cell (top, left cell). That cell causes all rows to be selected. Instead, I want to stop it from selecting all rows. I see an event for RowHeaderSelect and ColumnHeaderSelect but not one for that top, left header cell.

Any ideas? Am I just being blind?

+1  A: 

This is the dissasembled code of what happens when you click that cell:

private void OnTopLeftHeaderMouseDown()
{
    if (this.MultiSelect)
    {
        this.SelectAll();
        if (-1 != this.ptCurrentCell.X)
        {
            this.SetCurrentCellAddressCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false, false, false);
        }
    }

In order for you to prevent this behavior you have 2 solutions:

  1. Disable multi selection (if your business logic permits)
  2. Inherit your own datagrid and override OnCellMouseDown (something like this)

    protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e) { if (e.RowIndex == -1 && e.ColumnIndex == -1) return; base.OnCellMouseDown(e); }

anchandra
Thanks for the response. I need full row select.The other is intriging but, unfortunately, the gridview still selected all the columns when I tried this before. I ended up unselecting the rows as a work around but not a very pretty one.
Greg Kendall
So you did the override and the selection still happened? I did a quick test myself and it seemed to work.
anchandra
A: 

You could gain some control over the click event using this hack :)

    private void dataGridView1_Click(object sender, EventArgs e)
    {
        MouseEventArgs args = (MouseEventArgs)e;
        DataGridView dgv = (DataGridView)sender;
        DataGridView.HitTestInfo hit = dgv.HitTest(args.X, args.Y);
        if (hit.Type == DataGridViewHitTestType.TopLeftHeader)
        {
            // do something here
        }
    }
Steve