Thursday, 31 December 2009

Change Label Width Dynamically

Ok so in the last exercise we clicked the button on the form, this then:

1) Calculated the form size at that moment
2) Set the label size to be in the form with equal distance between the start and end of the label with repsect to the form edges.
3) Wrapped the text to fit.

Now the limitation was that if you moved the form's width with your mouse the label width would stay the same and so you wouldn't see the ends of the wrapped text as you decreased the form width.

1) To make this a dynamic setting take the code from the button click event and copy it to a text editor (Word, Notepad etc).
2) Delete the code
3) Go to the code window and in the top left drop down menu pick (frm1 events)
4) In the right hand drop down pick the resize event
5) In the event handler for the resize event paste the code you copied from the button click event.
6) Take out (cut) the line where you populate the label and paste it into the button click event.
7) Save and run the application

So your click event should only have this code in it:

lbl1.Text = "I am populating the label with some text now.... and I am typing more text here to increase the width of the string beyond the width of the screen. This is to show how the label can be wrapped so that it does not print off the screen."

Your resize event should have this code in it:

Can you see in the very last line of code that a new drawing size is being created and put in the lbl1.maximumsize property? The variable value we used in the original formwidth variable will change as we change the form width

When you run it you should be able to decrease the width of the form and the label text will now shrink or increase to fit, the text line breaks will increase or decrease depending on the width of the form. It will get to a point where, if you are decreasing the width of the form to such as extent, the height of the form, which is fixed, will not be able to expand to contain all the text and it will be pushed out the bottom of the form.

Label Being Decreased to Small Width (Note the label text wrapping to fit). Any smaller than this width and the text will start to be pushed off the bottom of the form.

Label Being Increased to Large Width(Note the label text increasing to fit):

What usually happens is a form will have many controls on it and the designer will want to contain the amount the user can decrease the width. We could stipulate a minimum size for the width so that it never went below this. Height will usually be static.

No comments:

Post a Comment