0

I have a listbox that gets text lines loaded in to it, if there are any text strings that are too long to fit in the listbox without being cut off I record the longest text length and I'm trying to increase the form size by the amount needed to make the list box wide enough to fit the text.

I've tried using this.Size, and this.Width, but neither seem to change anything, it just remembers whatever the form size is manually resized to the next time the app is reopened.

(I added debug text before and after the this.Size setting and I can see that the this.Size variable does actually get changed, but the change doesn't affect the window's size on screen.)

if (longesttextline > 32)
        {
            this.Size = new Size(newsize, this.Size.Height);
        }
        else
        {
            this.Size = new Size(this.MinimumSize.Width, this.Size.Height);
        }
  • Does this help: https://stackoverflow.com/questions/13064350/change-form-size-at-runtime-in-c-sharp – ChrisBD Mar 23 '22 at 16:21
  • Any chance you also have `MaximumSize` set, and `newsize` is bigger than the max width? – evilmandarine Mar 23 '22 at 16:22
  • Can you share a little bit more content? Maybe debug the code... I think the line is not executed, or longesttextline may never be greater than 32 – Martin Bartolomé Mar 23 '22 at 16:23
  • @ChrisBD Looks like the main idea of those answers is suggesting to use the "new Size(width, height)" format that I'm already using. – Steven_B86 Mar 23 '22 at 16:34
  • MaximumSize is not set (at default 0,0). The lines get executed, like I said I added debug text and a message box that show the Size setting changes after I set it, but it just doesn't update the window's size. If the size doesn't get bigger than 32, it should still fire the else statement causing it to resize back to minimumsize.width, but it doesn't it just stays at whatever size it was manually resized to previously. – Steven_B86 Mar 23 '22 at 16:40
  • i created a new form with a Button and the click event raises this code and it works: ```this.Size = new Size(this.Size.Width +10, this.Size.Height);``` – Martin Bartolomé Mar 23 '22 at 16:51
  • It'll be a thread context issue. You can only make changes to the UI on the same thread, hence why the button click will work. You'll need perhaps need to invoke a function to change the form size. – ChrisBD Mar 23 '22 at 17:59
  • So right now it's in a function that is called by the main function, so it is supposed to trigger when loaded. Putting the same function call in a test button works. How do I get it to be able to dynamically set the form width when it loads? I tried moving it to the form's "Load" event, that didn't work either. – Steven_B86 Mar 23 '22 at 18:17
  • @Steven_B86 Are you calling this function after you call `Application.Run(form);`? Else I suggest you show us the whole code. – evilmandarine Mar 23 '22 at 22:31

0 Answers0