使用DataGridView的MouseDown事件来测试是否单击了鼠标右键,如果是,则使用关联的HitTestInfo属性来确定是否单击了单元格,行或列.使用此信息显示所需的ContextMenuStrip.
这是一个示例MouseDown事件.要尝试该示例,请在表单上删除DataGridView和三个ContentMenuStrips.将ContentMenuStrips命名为mnuCell,mnuRow和mnuColumn.
Private Sub DataGridView1_MouseDown(ByVal sender As System.Object,ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown If e.Button = Windows.Forms.MouseButtons.Right Then Dim ht As DataGridView.HitTestInfo ht = Me.DataGridView1.HitTest(e.X,e.Y) If ht.Type = DataGridViewHitTestType.Cell Then DataGridView1.ContextMenuStrip = mnuCell mnuCell.Items(0).Text = String.Format("This is the cell at {0},{1}",ht.ColumnIndex,ht.RowIndex) ElseIf ht.Type = DataGridViewHitTestType.RowHeader Then DataGridView1.ContextMenuStrip = mnuRow mnuRow.Items(0).Text = "This is row " + ht.RowIndex.ToString() ElseIf ht.Type = DataGridViewHitTestType.ColumnHeader Then DataGridView1.ContextMenuStrip = mnuColumn mnuColumn.Items(0).Text = "This is col " + ht.ColumnIndex.ToString() End If End If End Sub
在这里,我将DataGridView的ContextMenuStrip属性分配给适用于右键单击的项(单元格,行或列)的ContextMenuStrip.为了演示如何进一步自定义ContextMenuStrips的行为,我还在每个ContentMenuStrips的菜单项中设置文本.