C# - DatagridView 和 ContextMenu
我有一个 datagridview,在其中显示有关产品的信息。我想在用户选择一个单元格然后右键单击该单元格时绑定一个上下文菜单。我有另一个上下文菜单,该菜单绑定到 datagridview 的列。如果用户右键单击某列,则会显示上下文菜单。
我已经尝试过这样的方法,但它不起作用。当用户右键单击单元格时会显示上下文菜单,但绑定到列标题的上下文菜单不起作用。
private void GridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
productContextMenu.Show(GridView1, e.Location);
}
}
我该如何做到这一点,以便当用户右键单击 datagridview 时显示出来?
提前非常感谢。
编辑
谢谢你的答案。我这样解决了问题:
private void GridView1_MouseUp(object sender, MouseEventArgs e)
{
DataGridView.HitTestInfo hitTestInfo;
if (e.Button == MouseButtons.Right)
{
hitTestInfo = GridView1.HitTest(e.X, e.Y);
if (hitTestInfo.Type == DataGridViewHitTestType.Cell)
{
productContextMenu.Show(GridView1, e.Location);
}
}
}
两个上下文菜单都显示。当我单击上下文菜单显示的列时,以及当我单击上下文菜单显示的单元格时。
I have a datagridview where I show infomation about products. I want to bind a contextmenu when the user selects a cell and then right clicks on that cell. I have another contextmenu and that one is bound to the columns of the datagridview. If a user right clicks on a column the contextmenu shows.
I have tried like this but it does not work. The context menu shows when the user right clicks on a cell, but the contextmenu that is bound to the column header does not work.
private void GridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
productContextMenu.Show(GridView1, e.Location);
}
}
How do I make it so that when the user right clicks on a datagridview shows up?
Many thanx in advance.
EDIT
Thnx for the answers. I solved the problem like this:
private void GridView1_MouseUp(object sender, MouseEventArgs e)
{
DataGridView.HitTestInfo hitTestInfo;
if (e.Button == MouseButtons.Right)
{
hitTestInfo = GridView1.HitTest(e.X, e.Y);
if (hitTestInfo.Type == DataGridViewHitTestType.Cell)
{
productContextMenu.Show(GridView1, e.Location);
}
}
}
Both the contextmenus shows. When I click on the column that context menu shows, and when I click on a cell that contextmenu shows.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个
或
Try this
or
对于相对位置的问题,还可以使用这样的办法:
For the problem with the relative position, you can also use this aproach: