tags:

views:

118

answers:

2

Hi,

I currently have a Textbox on a Windows Forms, and I need to dynamically add a PictureBox box control at the right of the Textbox.

I create the PictureBox programmatically and I when setting the location of the PictureBox, i'm setting like this:

pBox.Location = new Point(tbControl.Location.X + ctrl.Width, ctrl.Location.Y);

So i'm setting the picture box to be located at the X location of the textbox PLUS the width of the textbox. However, since the textbox has an anchor property set to right, its width increases to fill the space between itself and the form border.

Problem is, that even though the textbox's width is visually bigger than the actual value of Textbox.Width. the Width property is not taking into account the extra width of being anchored.

I already tried properties like Textbox.Bounds.Width, Textbox.ClientSize.Width, Textbox.DisplayRectangle.Width, etc. with no luck. All of those properties return the original Width of the control without taking into account the resized width due to the Anchor property.

Does anyone know how I can determine the real size of the textbox? Thank you

A: 

These should be returning the adjusted size. Either you are referring to the wrong textbox, or you are doing the query before the size has actually changed.

John Knoeller
I think you're right John...which is weird, since I'd think that the controls are expanded before the form is displayed (my program is already maximized when i open the new form), but it appears my proccess of adding the controls is happening before the textboxes are expanded.Any ideas on how to make it happen after the controls are anchored?
silverCORE
If you subscribe to SizeChanged notification, that should be late enough.
John Knoeller
Hey John. nobugz's solution worked, but I'm curious about the approach you suggested (for learning's sake). Did you mean to redraw or reposition the picturebox in the SizeChanged event of the textbox?
silverCORE
I mean wait for the SizeChanged notification on the textbox before you ask for its width. But nobugz's suggestion is a better solution anyway.
John Knoeller
+2  A: 

The Width property always tracks the current width of a control, whether it is anchored or not. However, the TextBox is going to grow when you make the container larger and that will make it overlap the PictureBox. You have to anchor the PB to the right as well.

Hans Passant
nobugz, I dont think anchoring the PB is the correct approach, since that would increase its width instead of moving the starting point of the pb. I just need to find a way to add the PBs until after the textboxes are expanded
silverCORE
No, it only increases width if it is anchored on both sides. Only anchor to the right.
Hans Passant
You were right nobugz! Anchoring the PB to the right did the trick. Thank you very much.
silverCORE
and this is why I love StackOverflow.
silverCORE