2013-07-09 67 views
0

[使用VB 2010/Winforms]获取DataGridView中“当前单元格”的X/Y坐标?

我有一个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坐标的情况下将它放在需要的地方附近)。

谢谢!

回答

4

试试下面的代码

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 
+0

感谢大卫......我感谢您抽出时间发布所有这些!只是测试了你的代码,这就是正确位置的“邻居”,所以如果这是唯一的问题,我可以抵消它。但不幸的是,更大的问题在于GUI大小调整时它会四处移动。我做了一些更多的在线研究,并在调整了一点之后找到了一个很好的解决方法。如果有人有兴趣,这是ShaneO的答案在这个链接 - > http://bytes.com/topic/visual-basic-net/answers/598859-how-get-currentcell-location-datagridview – NotQuiteThereYet

+0

GetCellDisplayRectangle方法返回一个矩形,它具有相对于其容器的位置。在这个例子中,它的容器就是Form。 –

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 
1

对于任何在未来为此而努力 - 这是真正的作品:

'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 
相关问题