【发布时间】:2018-01-25 15:29:21
【问题描述】:
我在 Windows 窗体中使用 Datagridview 来显示一些数据。 按下按钮后,数据会在后台加载。 当我第一次按下按钮时,这工作正常。
但我需要能够在不关闭表单的情况下一次又一次地执行此操作。 无论我尝试什么,在第二次按下 ok 后,我的 datagridview 都会变成白色的地面,上面有大红色的 x。我想清空/重置所有内容。
这是我的代码的精简版:
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()
【问题讨论】:
标签: powershell arraylist datagridview runspace