DataGridView鼠标单击空白区时如何清除选中状态?

解决方案 »

  1.   

    我不知道怎么上传图片。
    DataGridView不可能全部区域刚好被数据行(单元格)填满啊,显示了数据的区域以外的部分就是我说的空白区。
      

  2.   

     Dgv_GCKC.Rows(1).Selected = False
      

  3.   

    if(!this.DataGridView.fouced)
    {
        DataGridView.CurrentCell=null;
    }
      

  4.   

    正确答案:
            public int GetRowIndexAt(int mouseLocation_Y)
            {
                if (dataGridView1.FirstDisplayedScrollingRowIndex < 0)
                {
                    return -1;   
                }
                if (dataGridView1.ColumnHeadersVisible == true && mouseLocation_Y <= dataGridView1.ColumnHeadersHeight)
                {
                    return -1;
                }
                int index = dataGridView1.FirstDisplayedScrollingRowIndex;
                int displayedCount = dataGridView1.DisplayedRowCount(true);
                for (int k = 1; k <= displayedCount; )    
                {
                    if (dataGridView1.Rows[index].Visible == true)
                    {
                        Rectangle rect = dataGridView1.GetRowDisplayRectangle(index, true);  // 取该区域的显示部分区域   
                        if (rect.Top <= mouseLocation_Y && mouseLocation_Y < rect.Bottom)
                        {
                            return index;
                        }
                        k++;    
                    }
                    index++;
                }
                return -1;
            }
    测试用代码:
    private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
    {
       if (GetRowIndexAt(e.Y) == -1)
       {
          MessageBox.Show("空白区");
          dataGridView1.CurrentCell = null;
       }
    }
      

  5.   

    感谢lzsh0622,你的方法是对的!
    多问一句,DataGridView有没有提供比较方便简单的接口来判断呢,而不必自己写这样的函数进行判断?
      

  6.   

    10楼好用对了 我加了皮肤控件 貌似
    if (dgv.Rows.Count > 0)
    { this.dgv.Rows[0].Selected = false; }
    只能写在load事件才可用..