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

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

问题描述

我想为 DataGridView CellsRowHeadersColumnHeaders 设置不同的 ContextMenuStrip>.

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 Cell、RowHeader 和 ColumnHeader 的不同 ContextMenuStrip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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