I'm using a Datagridview inside a windows form to display some data. The data is loaded in the background after pressing a button. This works fine when I press the button for the first time.
But I need to be able, to do this again and again without closing the form. No matter what I try, after pressing ok a second time, my datagridview turns into white ground with big red x across it. I would like to empty/reset everything.
Here is a cut down version of my code:
Add-Type -AssemblyName System.Windows.Forms
$sync = [Hashtable]::Synchronized(@{})
$backgroundTask = {
$task1 = [PowerShell]::Create().AddScript({
#here I would like to clear all data from a previous execution. But nothing worked.
$softwareQuery = Get-WMIObject -ComputerName localhost -Class Win32_Product | Select Name
$softwareList = New-Object System.collections.ArrayList
$softwareList.AddRange($softwareQuery)
$sync.softwareTable.DataSource = $softwareList
})
$runspace = [RunspaceFactory]::CreateRunspace()
$runspace.ApartmentState = "STA"
$runspace.ThreadOptions = "ReuseThread"
$runspace.Open()
$runspace.SessionStateProxy.SetVariable("sync", $sync)
$task1.Runspace = $runspace
$task1.BeginInvoke()
}
$mainForm = New-Object system.Windows.Forms.Form
$mainForm.Size = New-Object System.Drawing.Size(900,600)
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(280,5)
$okButton.Size = New-Object System.Drawing.Size(75,20)
$okButton.Text = "OK"
$okButton.Add_Click($backgroundTask) ;
$mainForm.Controls.Add($okButton)
$softwareTable = New-Object System.Windows.Forms.DataGridView -Property @{
Location=New-Object System.Drawing.Point(5,30)
Size=New-Object System.Drawing.Size(840,360)
ColumnHeadersVisible = $true
}
$mainForm.Controls.Add($softwareTable)
$sync.softwareTable = $softwareTable
$mainForm.ShowDialog()