您的位置:首页 > 编程语言 > C#

C# dataGridView右键菜单

2010-11-11 23:12 309 查看
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边框行列的情况
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: