开发者

C# Label Properties won't update upon resize

I recently started getting acquainted with Visual Studio 2010 and C# for an internship. C# doesn't include a built-in InputBox function, so I made my own form, with a text box, two buttons and a simple label.

I have a function set up to allow the programmer to call the form in regular format (where the user enters input via the textbox) or yes/no format (where the form just displays a question and the yes and no buttons).

When I switch over to yes/no format, I want to center the label programmatically. I've been using the code:

labelNote.Left = inputBox.Left + (inputBox.Width / 2) - (labelNote.Width / 2);

This should put the center of the note in the center of the form. However, if the contents of the label change (making the new label longer 开发者_高级运维or shorter) the properties don't update to reflect the new size. It won't center unless it includes the original text. Is there some way to force an update? I foresee this becoming a problem with positioning objects for scalability in the future.

Thank you for your time


I'm assuming you have the sizing within an actionlistener. Specifically the forms' resize action listener. Then whenever the form is resized it is called and all of you code is recalled. Then to force an update from somewhere else you just have to call the actionlistener.

Actionlistener:

Private Sub formName_Resize(ByVal sender As Object, ByVal e As  EventArgs) Handles MyBase.Resize

Calls actionlistener:

formName_Resize(sender, e)


Well, you could attach an event to Label.TextChanged. Frankly it would be better to change the TextAlign or something like that though: try to perform the layout in a declarative fashion instead of doing it explicitly through code. That tends to make things work rather better.

I've found the [TableLayoutPanel]1 control to be reasonably easy to work with - most of the time (and occasionally a complete pain).


It turns out that I made a stupid mistake (a common theme for me in debugging. The really small stuff goes unnoticed for the longest amount of time).

The label resizing was not the issue. The issue was the order in which I changed the contents of the label and then called the function to calculate its new location. I was calling the location calculation first, so it found where to center the label based on the old contents. I didn't notice for so long, because the text was changing properly. I took it for granted that the functions were being called in the correct order.

So, when it doubt, check the order in which you're writing your code. Thanks for you help anyway, everyone. I ended up finding out some neat things that could be applicable to other scenarios (such as the MeasureString function in the Graphics class).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜