确定放入的tablelayoutpanel项目

时间:2014-01-09 18:52:04

标签: vb.net winforms

我正在尝试确定用户将对象放入的TableLayoutPanel的哪个单元格(行/列)。目前我只能找到如何确定物品掉落位置的坐标:

Dim location As Point = TableLayoutPanel1.PointToClient(New Point(e.X, e.Y)) 

但是我无法弄清楚如何找到所在的单元格。我确实找到了命令GetCellPosition并尝试使用坐标;然而,这也没有用。

TableLayoutPanel1.GetCellPosition(location)

2 个答案:

答案 0 :(得分:3)

您可以尝试此功能:

Private Function GetCellFromPoint(p As Point) As Point
  Dim result As New Point(-1, -1)
  Dim colWidths As Integer() = tlp.GetColumnWidths()
  Dim rowHeights As Integer() = tlp.GetRowHeights()
  Dim top As Integer = 0
  For y As Integer = 0 To rowHeights.Length - 1
    Dim left As Integer = 0
    For x As Integer = 0 To colWidths.Length - 1
      If New Rectangle(left, top, colWidths(x), rowHeights(y)).Contains(p) Then
        result = New Point(x, y)
      End If
      left += colWidths(x)
    Next
    top += rowHeights(y)
  Next
  Return result
End Function

它只是循环遍历行和列,以查看传入的点是否在现有单元格内。但请注意,GetColumnWidthsGetRowHeights未显示在intellisense下拉列表中。

用法:

Private Sub tlp_MouseMove(sender As Object, e As MouseEventArgs) _
                          Handles tlp.MouseMove
  Me.Text = GetCellFromPoint(e.Location).ToString
End Sub

BTW,GetCellPosition期望控件作为参数传递,而不是Point结构。

您也可以在此函数中使用TableLayoutPanelCellPosition代替Point,因为这是GetCellPosition在其函数中返回的内容。

答案 1 :(得分:0)

我已经使用过这个功能(万分感谢),但我发现了一个问题。要正确定义对象垂直的单元格,我们需要考虑屏幕中TableLayoutPanel的位置。我已经解决了这个问题,声明了p(在DragDrop事件中用e.X和e.Y构建)和r(屏幕中TableLayoutPanel位置的引用)。 然后你必须分配p = p - r并将该P发送到函数GetCellFromPoint(p)。

Private Sub TableLayoutPanel1_DragDrop(sender As Object, e As DragEventArgs) Handles TableLayoutPanel1.DragDrop
Dim p As New Point(e.X, e.Y)
Dim r As Point
r = TableLayoutPanel1.PointToScreen(New Point(0, 0))
p.X = p.X - r.X
p.Y = p.Y - r.Y
MessageBox.Show(GetCellFromPoint(p).ToString)
End Sub