问题描述
我在dataGridView上附加了一个contextMenuStrip,当我右键单击daaGridView上的任何位置(包括标题和没有数据行的空白区域)时,都会出现contextMenuStrip.
I have a contextMenuStrip attached to a dataGridView and when I right-click any where on the daaGridView including the header and the blank area that doesn't have any data rows the contextMenuStrip appears.
我只想在数据行上单击鼠标右键时显示contextMenuStrip.我该怎么办?
I want the contextMenuStrip to appear when I right-click on the data rows ONLY. How can I do this?
感谢您的帮助.
推荐答案
您需要使用datagridview的HitTest方法来确定是否单击了任何数据行.在网格的Mousedown事件中,使用以下代码:
You need to use HitTest method of datagridview in order to find out if any datarow is clicked or not. Within Mousedown event of the grid, use the following code:
var info = dataGrid1.HitTest(e.X,e.Y);
if(info.RowIndex!=-1)// datarow is clicked.
contextMenu.Show(dataGrid1, e.Location);
info.RowIndex对于列标题或背景区域将为-1.另外,不要在设计时预设dataGrid1.ContextMenu属性(将其保留为未分配状态).因此,默认情况下,右键单击时dataGrid1不会显示contextMenu.
info.RowIndex will be -1 for columnheaders or background area. Also don't preset dataGrid1.ContextMenu property at design time (leave it unassigned). So that your dataGrid1 can not show contextMenu by default on right click.
这篇关于我可以只为列而不是dataGridView中的标头制作contextMenuStrip吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!