Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding many Labels to a WinForm slow

I'm playing around with WinForms and would like to add alot of Labels with a border so to create some sort of grid. Now, adding the Labels is easy enough:

for (int i = 0; i < 60; i++)
        {
            for (int j = 0; j < 60; j++)
            {
                var label = new Label();
                label.BorderStyle = BorderStyle.FixedSingle;
                label.SetBounds(i * 10, j * 10, 10, 10);
                this.Controls.Add(label);
            }
        }

But this is really, really slow. I can almost see each of the squares being drawn individually. When creating an array of controls and adding them using Controls.AddRange() the same thing happens.

Now since I'm drawing 3600 controls, I can imagine it being somewhat slow, but I can't help but think there's a better way to do this. When I time the Control.AddRange() statement, the Stopwatch tells me it's taking about 1600ms. The actual drawing seems to take a bit longer.

Is there any way to work around this and keep an application with alot of controls snappy and responsive?

like image 764
fuaaark Avatar asked Jan 28 '26 18:01

fuaaark


1 Answers

Do you NEED the individual controls? With tasks like this I usually override onpaint in a usercontrol and draw the text and boxes myself. Then if you need user input, just position a single textbox ontop of your custom text.

like image 58
Mattias Åslund Avatar answered Jan 30 '26 06:01

Mattias Åslund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!