[使用VB 2010 / Winforms]
我有一个包含多个列的DataGridView。它没有绑定,也没有连接到任何类型的数据库或任何东西 - 我只是根据用户输入逐个填充它。
所以,无论如何,DGV中的一列是“image”类型(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坐标时把它放在需要的地方附近。)
谢谢!
答案 0 :(得分:5)
尝试以下代码
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
答案 1 :(得分:3)
对于任何在未来苦苦挣扎的人 - 这才是真正有效的:
'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
答案 2 :(得分: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