2

[使用 VB 2010 / Winforms]

我有一个包含几列的 DataGridView。它是未绑定的,也没有连接到任何类型的数据库或任何东西——我只是根据用户输入逐个单元格地填充它。

所以无论如何,DGV 中的一列是“图像”类型(DataGridViewImageColumn)。

我想要做的是每当单击图像单元格之一时,都会在单击图像单元格的确切位置显示上下文菜单条。

这是我到目前为止所得到的......

Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick

        Dim columnName As String = DataGridView1.Columns(e.ColumnIndex).Name
        If columnName = "Image" Then 
         Me.Status_ContextMenuStrip1.Show(Me.DataGridView1.CurrentCell.ContentBounds.Location) ' <-- This isn't right, but I must be close!
        End If

End Sub

当我运行上面的代码并单击图像单元格时,会出现上下文菜单,但它出现在屏幕的最左上角。如何让它出现在单击的单元格所在的确切位置?我实际上希望它出现在单击的单元格下方,以便它具有与组合框“下拉”类似的视觉效果(并且我知道如何偏移 X 和 Y 坐标,只要我能弄清楚如何将它放在需要的位置附近)。

谢谢!

4

3 回答 3

7

试试下面的代码

Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    Dim columnName As String = DataGridView1.Columns(e.ColumnIndex).Name

    If columnName = "Image" Then
        Dim RowHeight1 As Integer = DataGridView1.Rows(e.RowIndex).Height
        Dim CellRectangle1 As Rectangle = DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, False)

        CellRectangle1.X += DataGridView1.Left
        CellRectangle1.Y += DataGridView1.Top + RowHeight1

        Dim DisplayPoint1 As Point = PointToScreen(New Point(CellRectangle1.X, CellRectangle1.Y))

        ContextMenuStrip1.Show(DisplayPoint1)
    End If
End Sub
于 2013-07-09T22:01:49.103 回答
5

对于任何在未来为此苦苦挣扎的人——这才是真正有效的:

'For forms
Dim f as New Form2
f.Location = DGV.PointToScreen(DGV.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, False).Location)

对于这篇文章的情况:

Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As
  Dim DisplayPoint1 As Point = DGV.PointToScreen(DGV.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, False).Location)
ContextMenuStrip1.Show(DisplayPoint1)
End Sub
于 2017-03-03T15:49:43.287 回答
0

尝试像这样更改您的代码..

Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick

    Dim columnName As String = DataGridView1.Columns(e.ColumnIndex).Name
    If columnName = "Image" Then 
       DataGridView1.CurrentCell = dgvDataDaftar.Rows(e.RowIndex).Cells(e.ColumnIndex)
       Me.Status_ContextMenuStrip1.Show(dgvDataDaftar, DataGridView1.PointToClient(Windows.Forms.Cursor.Position))
    End If

End Sub
于 2013-07-10T02:43:30.603 回答