Zarathos Zarathos - 1 month ago 12
C# Question

Find position of a control relative to another control

Let's say I have a custom

UserControl
. It contains a
TableLayoutPanel
with
Dock
property set to
Fill
. The
TableLayoutPanel
has a 3 rows and 2 columns. In the cell (0,1) I have a
Panel
(
Margin
3) with a
TextBox
(
Margin
3) inside it. How can I get the bounds of the
TextBox
relative to the
UserControl
? Measuring it by hand it should be something like X=3 and Y=29, with Width=TextBox.Width and Height=TextBox.Height.

Answer

You can use this code:

var c = textBox1;
var p1 = c.Parent.PointToScreen(c.Location);
var p2 = this.PointToScreen(new Point(0, 0));
var p = new Point(p1.X - p2.X, p1.Y - p2.Y);
var bounds = new Rectangle(p, c.Size);

I suppose this code is executing in UserControl1, then bounds is what you are looking for.

In above code p1 is screen location of textBox1 and p2 is screen location of the first point of top container (UserControl1). So the difference between these points is the relative location of textBox1. Then since the size is not relative then bounds would be new Rectangle(p, c.Size);.

The code will work with any hierarchy regardless of depth.

Comments