Thursday, March 31, 2011

Add Controls to WinForms dynamically in another Thread

Hi all,

I have a Winform that contains a datagridview, bindingsource, file explorer control, etc...

I need add several controls (Custom UserControls) to a Panel dynamically (like Panel.Controls.Add(...)). This process can be slow.

I want to show to the user a message (waiting).

What is the best way? I use Backgroundworker but I have problems, my application not responds and datagridview not shows scrollbar vertical, and another strange things.

Thanks in advance, kind regards

From stackoverflow
  • A thread is probably not your best bet for gui operations like this. All controls should be created on the same thread.

    Instead put a statusbar control at the bottom of your form. On the statusbar, include a progress bar and a label. When adding a control, indicate this on the statusbar by including a message in the label and incrementing the progressbar.

  • any sample code, please ?? Thanks.

  • I doubt that adding controls to a WinForm could be slow. IMHO what probably degrades the performance is fetching the data that is bound to them. So you can for example load the data in a new thread and once it is loaded, bind it to the control:

    ThreadPool.QueueUserWorkItem(o =>
    {
        // Simulate some expensive data fetch.
        Thread.Sleep(1000);
        string[] data = new[] { "value1", "value2" };
    
        if (InvokeRequired)
        {
            Action a = () => { listBox1.DataSource = data; };
            // Ensure that all UI updates are done on the main thread
            Invoke(a);
        }
    });
    
  • I need add several controls (Custom UserControls) to a Panel dinamically (like Panel.Controls.Add(...)). This process can be slow, because each user control contain one thumbnail of PDF file. The user control contains Container of XPdfViewer (a COM library).

    Can I create custom user controls (container, wrapper) in an another thread and add it (add the control to main form) in Main Thread ??

    For (i = 0 to Num Thumbnails) { 1. Create control in Thread A

    1. Add Control in Main Thread (UI)

    }

    I want to show to the user a message (waiting).

    Thanks in advance, kind regards

    Please, any sample good source code.

0 comments:

Post a Comment