Friday, November 18, 2011

Finding absolute position of a control on a windows form

I wanted to overlay a datagridview with a dropdown depending on certain conditions, so using a datagridview combo box which does it always didnt work

So I had the bright idea of creating a combobox on the fly, and I wanted it to land right on the cell.
The trick was the cell is in a datagrid, and the datagrid is nested in some panels

So I had to find out where I was from the base of the form.
This code does that

Private Function GetPositionInForm(ByVal ctrl As Control) As Point
        Dim P As Point = ctrl.Location
        Dim Parent As Control = ctrl.Parent
        While Parent.Name <> ctrl.FindForm.Name
            P.Offset(Parent.Location.X, Parent.Location.Y)
            Parent = Parent.Parent
        End While
        Return P
    End Function

When using it in a grid, you need the final touch of the row and cell position

Dim NewPosition As Point = GetPositionInForm(dgvSourceTakeoff)
Dim CellRectangle As Rectangle = grid.GetCellDisplayRectangle(col,row,True)
NewPosition.X += CellRectangle.Location.X
NewPosition.Y += CellRectangle.Location.Y
cboSelector.Location = NewPosition

No comments:

Post a Comment