creating controls in a background thread

grambowk

New member
Joined
Apr 30, 2006
Messages
1
Programming Experience
1-3
Not sure if this is the right forum but hopefully someone can help.

I'm using .NET 2.0 and am working in a WinForms project.

Essentially, what I'm trying to do is create a number (indeterminate) of data grids in a background thread, populate them, and then somehow pass the grids back to the primary thread so that I can place them on my UI.

Because the number of grids I'm creating is unknown and also because populating them could take a while (due to large amounts) of data I cannot create the grids beforehand, which is why I'm trying to create them in the background thread.

Normally, when accessing controls created in a thread other than the one you're in I'd using the Invoke method but I'm not sure that's the case when trying to pass controls from one thread to the other. Plus, my attempt to do so doesn't work.

Here's a section of my code, with inline comments. If anyone can tell me what I might be doing wrong or how to best go about achieving the desired results that would be appreciated.

Note that I'm also creating a splitter control in my background thread and I successfully manage to create it on the UI.

VB.NET:
[INDENT]'this is running in the background thread
[/INDENT]Private Sub CreateResultsGrid()
[INDENT][INDENT]Dim ResultsGrid As New DataGrid    'Create a new data grid
[/INDENT]Dim Seperator As New Splitter    'and a new splitter
[/INDENT][INDENT]         'code for intialising and populating grid goes below
        '***
        '***
        '***
        '***
[/INDENT][INDENT]         'prepare to marshal back to primary thread
[/INDENT][INDENT]         Dim ObjArray(1) As Object[INDENT]ObjArray(0) = ResultsGrid 
[/INDENT][/INDENT][INDENT][INDENT]ObjArray(1) = Seperator 
[/INDENT][/INDENT][INDENT][INDENT]ResultsPanel.Invoke(New Grid(AddressOf AddGrid), mySplitterGridArray)[/INDENT][/INDENT]        End Sub


Public Delegate Sub Grid(ByVal myGrid As DataGrid, ByVal mySeperator As Splitter)

Public Sub AddPanelGrid(ByVal ResultsGrid As DataGrid, ByVal Seperator As Splitter)


        'add the splitter and grid to the ResultsPanel

            ResultsPanel.Controls.Add(Seperator)        'THIS WORKS  
            ResultsPanel.Controls.Add(ResultsGrid)    'THIS DOES NOT WORK: "Cross-thread operation not valid"

    
          

        End Sub 'DelegateMethod

Thanks,

Karl
 
Back
Top