I have a folder with a large amount of files inside of it. I want to be able to render each of my files as a button. And when I click on the button something will happen.
private void Form1_Load(object sender, EventArgs e)
{
int x = 10;
int y = 10;
/// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(@"c:\lotsofDocs");
foreach (string fileName in fileEntries)
{
// do something with fileName
Button newbotton = new Button();
newbotton.AutoSize = true;
newbotton.Text = fileName;
panel1.Controls.Add(newbotton);
newbotton.Location = new Point(x, y);
x += 150;
if (x == 760)
{
y += 50;
x = 10;
}
}
As you can see there's nothing crazy in the code. I have a panel on a form and I've set auto scroll on the panel to true and auto size to false. This causes the form to maintain size and the buttons (some of them anyway) to get rendered off the form and I can scroll down to them.
All good so far.
If I have 100 or 200 file everything is ok, if I have 1932 files it takes about 10 seconds to render all the buttons.
I've read the follow question Super slow C# custom control and I understand that the approach I'm using might not be the best to use here.
And now the question at last: how does windows explorer handle this? If I open this folder in Windows explorer it opens instantly. What type of control is windows explorer using? Or is it doing it in a completly different way to me.
Thanks
Very long lists of controls are usually implemented via virtualised controls. That means that if only 20 buttons fit on the screen it only creates 20 buttons or so. When you scroll around it reuses the same 20 buttons with new data in them.
Controls can be very slow to create and manage in large numbers as they are usually added to a simple list or hierarchy (and are quite complex individually).
Better off managing a smaller set of buttons yourself to show a very long list of data. More work obviously, but the end result is lightning fast compared to the "simple way".
If you don't want to DIY, try a third party control. As an example the Telerik virtualised Tree, List and Grid controls can display a million records with no slowdown. Take a look at their Winforms grid here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With