Search code examples
c#resizelabelcentervisual-studio-2010

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


Solution

  • 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).