DataGridView通过鼠标右键选中行

新方法DataGridView通过鼠标右键选中行

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
        {
            if (e.RowIndex >= 0)
            {
                dataGridView1.ClearSelection();
                dataGridView1.Rows[e.RowIndex].Selected = true;
                dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
            }
        }
    }
}
在DataGridView中的CurrentRow属性为只读,且其Index也不能动态设置,故只能在DataGridView中用左键来选择行,从而实现当前行的定位。
现在要实现在DataGridView中单击右键实现左键的功能,代码如下:
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
    {
        dataGridView1.CurrentRow.Selected = false;
        dataGridView1.Rows[e.RowIndex].Selected = true;
    }
}
DatagridView的CellMouseDown事件添加如上代码,在不考虑注释代码的情况下,可以实现对当前选中行的不显示选中,而对鼠标右击的行实现选中
这样存在一个问题,CurrentRow的属性仍然为之前的哪个值,即使将鼠标右键选中的行的Selected设置为True也不能改变。
而在将注释代码注销后即可同时改变CurrentRow的属性,这样以后编码方便多了!
当然在对CurrentCell赋值的时候别忘了判断鼠标右击到DataGridView边框行列的情况
以上本文来自CSDN博客:http://blog.csdn.net/Adi_liu/archive/2009/01/07/3725230.aspx

<===========================================>

由于本人要实现的是在dataGridView中通过右键所在位置是否为数据行,没有则禁用部份菜单项。
以上代码无法判断右键是否在空置,代码修改如下:

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
   DataGridView.HitTestInfo rows = this.dataGridView1.HitTest(e.X, e.Y);
   if (e.Button == MouseButtons.Right)
 {
   if (rows.RowIndex > -1)
     {
           this.dataGridView1.ClearSelection();
          this.dataGridView1.CurrentRow.Selected = false;
          this.dataGridView1.Rows[rows.RowIndex].Selected = true;
       }
        else
        {
       }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值