将ContextMenuStrip分配给特定列 [英] Assign ContextMenuStrip to specific column

查看:90
本文介绍了将ContextMenuStrip分配给特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个分配给DataGridView的ContextMenuStrip,如下所示:

 dgvDataGridView.ContextMenuStrip = contextMenuStrip1; 

至于现在,我可以单击DataGridView中的任何列,并显示相同的ContextMenuStrip。现在,相反,我想拥有它,以便只有当我点击一个特定列时才显示contextMenuStrip1。


所以我试过这个:

 dgvDataGridView.Columns [" COMMENT"]。ContextMenuStrip = contextMenuStrip1; 

然后我收到此错误消息:
$
"对象引用未设置为对象的实例"。


为什么我会收到此消息?实际上有一个具有该名称的列。





解决方案

你应该这样做:

1.处理点击dgvDataGridView的事件

2.检查鼠标按钮是否正确。如果是这样,请显示contextMenuStrip1

3.如果您想知道点击的dgvDataGridView的列和行,请获取MouseEventArgument的ColumnIndex和RowIndex。



这是一个示例代码(这是VB.NET,但它会有所帮助):
$

 

Private Sub dgvDataGridView_CellMouseClick( sender As Object,e As DataGridViewCellMouseEventArgs)_
句柄dgvDataGridView.CellMouseClick
Me.hitRow = e.RowIndex
Me.hitCol = e.ColumnIndex
'---列见出しなら处理を抜ける
如果(Me.hitRow = -1)那么
退出Sub
结束如果
'---
选择案例e.Button

Case = MouseButtons.Right
' - ▼右键单击:显示ContextMenuStrip
Me.ContextMenu_DGV.Show(Cursor.Position,ToolStripDropDownDirection.BelowRight)
Case = MouseButtons .Left
' - ▼左键点击:做点什么
结束选择
结束子




Currently I have a one ContextMenuStrip assigned to a DataGridView like this:

dgvDataGridView.ContextMenuStrip = contextMenuStrip1;

As for now I could click any column in the DataGridView and the same ContextMenuStrip shows up. Now, instead, I would like to have it so that contextMenuStrip1 only shows up if I click a specifik column.

So I did try this:

dgvDataGridView.Columns["COMMENT"].ContextMenuStrip = contextMenuStrip1;

Then I get this error message:
"Object Reference not set to an instance of an Object".

Why am I getting this? There's actually a column with that name.

解决方案

You should do:
1. handle an event of clicking on dgvDataGridView
2. check if mouse button is Right. If so, show contextMenuStrip1
3. if you want to know column and row of dgvDataGridView clicked, get ColumnIndex and RowIndex of MouseEventArgument.

This is a sample code (This is VB.NET, but it would be something helpful):

Private Sub dgvDataGridView_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) _
Handles dgvDataGridView.CellMouseClick Me.hitRow = e.RowIndex Me.hitCol = e.ColumnIndex ' --- 列見出しなら処理を抜ける If (Me.hitRow = -1) Then Exit Sub End If ' ---
Select case e.Button

Case = MouseButtons.Right ' --▼ Right Click: show ContextMenuStrip Me.ContextMenu_DGV.Show(Cursor.Position, ToolStripDropDownDirection.BelowRight) Case = MouseButtons.Left ' --▼ Left Click: do something End Select End Sub



这篇关于将ContextMenuStrip分配给特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆