突出显示 DataGridView 中选定的单元格?
在下面的代码中,当用户右键单击 DataGridView 中的单元格时,我将显示一个上下文菜单。我还希望用户右键单击以更改背景颜色的单元格,以便他们可以看到他们“右键单击选择”的单元格。有没有办法在下面的代码中添加一些内容以便发生这种情况?
private void dataGridView2_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu m = new ContextMenu();
MenuItem mnuCopy = new MenuItem("Copy");
mnuCopy.Click += new EventHandler(mnuCopy_Click);
m.MenuItems.Add(mnuCopy);
int currentMouseOverRow = dataGridView2.HitTest(e.X, e.Y).RowIndex;
m.Show(dataGridView2, new Point(e.X, e.Y));
}
}
In my code below, I'm showing a context menu when the user right-clicks on a cell in my DataGridView. I'd also like the cell that the user right-clicks on to change background color so that they can see the cell they've "right-click selected". Is there a way to add something to my code below so that this occurs?
private void dataGridView2_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu m = new ContextMenu();
MenuItem mnuCopy = new MenuItem("Copy");
mnuCopy.Click += new EventHandler(mnuCopy_Click);
m.MenuItems.Add(mnuCopy);
int currentMouseOverRow = dataGridView2.HitTest(e.X, e.Y).RowIndex;
m.Show(dataGridView2, new Point(e.X, e.Y));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很明显,您已经侵入了我的工作站并看到了我最近所做的一些工作。我有点夸张,因为我没有完全按照你想要做的去做,但经过一些调整我就能够做到。
我将修改您的
MouseClick
事件以获取 DGV 的CurrentCell
。获得后,将CurrentCell
的Style
属性设置为您想要的SelectionBackColor
。像这样的事情:上面的内容有点“空中代码”(换句话说,我没有尝试将它与您的代码合并并运行它),但我希望您明白这一点。请注意,我通过点击测试检查了单元格是否被单击;如果您不这样做并且用户没有单击单元格,您可能会遇到一些问题。
现在存在的问题是,此代码将更改您右键单击的所有单元格的
SelectionBackColor
。在 DGV 的CellLeave
事件中恢复此属性很容易:我必须记住这种视觉效果;感谢您提出问题。
So obviously you've hacked into my workstation and have seen some of the stuff I've worked on recently. I exaggerate a bit because I didn't do exactly what you're trying to do but with a little bit of tweaking I was able to.
I would modify your
MouseClick
event to get the DGV'sCurrentCell
. Once you have it, set theCurrentCell
'sStyle
property with theSelectionBackColor
you want. Something like this:The above is a bit 'air code-y' (in other words I haven't attempted to merge it with your code and run it) but I hope you get the idea. Notice that I check through the hit test that a cell was clicked; if you don't do this and the user does not click a cell you might have some problems.
Now there's the problem that this code will change the
SelectionBackColor
for the all the cells you right click. That's easy to restore this property in the DGV'sCellLeave
event:I'll have to remember this visual affect; thanks for asking the question.