I am building a winform Application. I have to create buttons dynamically based on data fetched from database. I followed following steps

Created UserControl
On UserControl_Load event I fetched data from database.
I populated the UserControl with buttons based on number of rows i get from the database.

The above approach proved too slow. The form loads slowly. It takes time to populate buttons. So Which is the best and optimised way to load controls dynamically in C# winforms?

here is my code

public ucFileCategoryPane()
        {
            InitializeComponent();
            PopulateNavPane();
        }

        public void PopulateNavPane()
        {
            tblFileController f = new tblFileController();
            List<tblFile> lfile = f.FileList();

            foreach (tblFile t in lfile)
            {
                vNavPaneItem vNavPaneItem2 = GetItemPanel(t);
                vnpFiles.Items.Add(vNavPaneItem2);
            }

            if (vnpFiles.Items.Count > 0)
            {
                string header = vnpFiles.Items[0].HeaderText;
                Connection.DbName = header;
                ListView li = CreateCategoryList(header);
                vnpFiles.Items[0].ItemPanel.Controls.Add(li);
            }
        }

        public vNavPaneItem GetItemPanel(tblFile t)
        {
            string ItemPanelName = "vip" + t.FileName;
            string ItemName = "vi" + t.FileName;
            string ItemText = t.FileName + " => Categories";
            vNavPaneItem vNavPaneItem2 = new vNavPaneItem();
            vNavPaneItem2.BackColor = System.Drawing.Color.White;
            vNavPaneItem2.HeaderText = t.FileName;
            vNavPaneItem2.ItemPanel.AutoScroll = true;
            vNavPaneItem2.ItemPanel.Location = new System.Drawing.Point(1, 30);
            vNavPaneItem2.ItemPanel.Name = ItemPanelName;
            vNavPaneItem2.ItemPanel.Size = new System.Drawing.Size(198, 168);
            vNavPaneItem2.ItemPanel.TabIndex = 1;
            vNavPaneItem2.Location = new System.Drawing.Point(0, 0);
            vNavPaneItem2.Name = ItemName;
            vNavPaneItem2.Size = new System.Drawing.Size(200, 199);
            vNavPaneItem2.TabIndex = 0;
            vNavPaneItem2.Text = ItemText;
            vNavPaneItem2.TooltipText = ItemText;
            vNavPaneItem2.Click += new EventHandler(vNavPaneItem2_Click);

            return vNavPaneItem2;
        }

How many buttons on average are you generating?

Deceptikon,

Number of buttons depends on number of rows fetched from DB

I understand that. What I want is an actual number that you expect on average, because that can affect the performance of your user control.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.