DataGridView override top,left header cell click (select all)

你说的曾经没有我的故事 提交于 2019-11-29 16:13:15
anchandra

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);
    }
    

I know this is late but hopefully it will help someone. The code below worked for me in a similar scenario.

    private void MyDataGridView_MouseUp(object sender, MouseEventArgs e)
    {
        DataGridView.HitTestInfo hitInfo = this.MyDataGridView.HitTest(e.X, e.Y);
        if (hitInfo.Type == DataGridViewHitTestType.TopLeftHeader)
        {
            MyDataGridView.ClearSelection();
        }
     }
Steve

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!