Havion
Havion

Reputation: 29

Dynamically constructed textbox positioning

I am building a program where you can create rectangles and modify their length based on a textbox that should appear slightly above the rectangle and appear /2 of its width.

So far with this program you can draw the rectangle using your mouse and I made it so when you release the mouse it runs a method and creates these dynamic textboxs.

public void mainCounter()
{
     Textbox aboveBox = new TextBox();
     aboveBox.Name = Convert.ToString(_mainRectangle.Width);
     aboveBox.Left = _mainRectangle.Width / 2;
     aboveBox.Top = _mainRectangle.Height + 5;
     panel1.Controls.Add(aboveBox);
}

So what I am wanting to happen should look something like a rectangle with a textbox hovering above the center of its head once drawn but what im getting is a textbox that is appearing on a set part of the Y axis and if i draw different rectangles it appears in different locations on the X axis but its always there at the same place on the Y axis.

Screen shot:

enter image description here

This could be just something stupid im doing again and I apologize if that is the case but any help would be great. Thanks guys!

Upvotes: 1

Views: 632

Answers (1)

Krumelur
Krumelur

Reputation: 32497

You got the coordinates wrong if you wanted to place the textbox centered. Note in particular you did not position the textbox in relation to the position of the rectangle (Left, Top), which I assume is an error.

If you want some object drawn adjacent to some other object, you should in general always do something like

A.Left = B.Left + ...
A.Top = B.Top + ...

Try this

Textbox aboveBox = new TextBox();
aboveBox.Name = Convert.ToString(_mainRectangle.Width);
aboveBox.Width = ...
aboveBox.Left = _mainRectangle.Left + (_mainRectangle.Width - aboveBox.Width) / 2;
aboveBox.Top = _mainRectangle.Top - aboveBox.Height - 5;
panel1.Controls.Add(aboveBox);

or something like it

Upvotes: 2

Related Questions