[使用VB 2010/Wforms]
我有一个包含多个列的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坐标)。
谢谢!
尝试以下代码
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
对于任何在未来与之斗争的人来说,这才是真正有效的:
'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
尝试这样更改代码。。
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