DataGridView单元格,RowHeader和ColumnHeader的不同ContextMenuStrip [英] Different ContextMenuStrip for DataGridView Cell, RowHeader and ColumnHeader

查看:95
本文介绍了DataGridView单元格,RowHeader和ColumnHeader的不同ContextMenuStrip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 DataGridView 单元格 ContextMenuStrip >, RowHeaders ColumnHeaders

I want to set different ContextMenuStrip for DataGridView Cells, RowHeaders and ColumnHeaders.

当我右键单击任何这些项目时,将显示不同的 ContextMenuStrip 。我该怎么做?

The idea is that when I right-click any of these items, a different ContextMenuStrip 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单元格,RowHeader和ColumnHeader的不同ContextMenuStrip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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