datagridview单元格,行标题栏和列标题的上下文菜单 [英] context menu for datagridview cell, rowheader and columnheader

查看:678
本文介绍了datagridview单元格,行标题栏和列标题的上下文菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为datagridview单元格,行标题和列标题设置不同的上下文菜单。
想法是当我右键单击任何这些项目时,将显示一个不同的上下文菜单。如何执行此操作?

I want to set different context menu for datagridview cells, rowheaders and columnheaders. The idea is that when I right-click any of these items, a different context menu is displayed. How do i do this?

推荐答案

使用DataGridView的 MouseDown 事件测试鼠标是否已被点击,如果使用相关的 HitTestInfo 属性来确定单元格,行或列是否已被单击。使用此信息显示您需要的ContextMenuStrip。

Use the DataGridView's MouseDown event to test if the right mouse has been clicked and if so use the associated HitTestInfo property to determine if a cell, row or column has been clicked. Use this information to display the ContextMenuStrip you need.

这是一个实例 MouseDown 事件。试试下面一个DataGridView和一个表单上的三个ContentMenuStrips。命名为ContentMenuStrips mnuCell,mnuRow和mnuColumn。

Here's an example MouseDown event that does this. To try the sample drop a DataGridView and three ContentMenuStrips on a form. Name the ContentMenuStrips mnuCell, mnuRow and 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菜单项中设置文本。

Here I'm assigning the DataGridView's ContextMenuStrip property to the ContextMenuStrip appropriate for the item right clicked (cell, row or column). To demonstrate how you might further customize the behavior of the ContextMenuStrips I'm also setting the text in each ContentMenuStrips' menu item.

这篇关于datagridview单元格,行标题栏和列标题的上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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