C# Reload/Redraw form upon settings update in dialog box

cwinforms

I have a C# Win Forms application where I dynamically draw buttons in a panel based on 2 properties in the class. Rows and Columns.

I also have a dialog box that opens, which sets those properties using 2 textboxes.

I have a button on that dialog box called "save" which upon pressing, updates the properties (rows, columns) in the main class to whatever values are set.

I want the main form to redraw the dynamically drawn buttons, based on the new settings applied (rows and columns). How can I do this?

edit:

Refresh is not working.

Another possibly important note: my dynamic drawing of buttons occurs in the "Form1_Load" method.

Best Answer

You have basically three ways to force the control to redraw itself, Refresh(), Update() and Invalidate(). As Adam Robinson points out, the easiest way to enable custom painting is to override the Paint event. Put all painting logic here. Use the Graphics object provided by the PaintEventArgs parameter.

So what's the difference between the above calls?

Invalidate marks the control (region, or rect) as in need of repainting, but doesn't immediately repaint (the repaint is triggered when everything else has been taken care of and the app becomes idle).

Update causes the control to immediately repaint if any portions have been invalidated.

Refresh causes the control to invalidate, and then update (i.e. immediately repaint itself).

I'd say it's a good habit to use Invalidate() unless you have specific needs to cater for. In most cases it will make your program more efficient. If you do this, you won't even need to have paint logic in your load event. Quite possibly this is being overwritten and invalidated before you even get your form visible, depending on what else you do in the Load event.

Related Topic