如何在PowerShell中清除和重用DataGridView?

时间:2018-01-25 15:29:22

标签: powershell arraylist datagridview runspace

我在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()

2 个答案:

答案 0 :(得分:0)

我认为其中一个问题可能是您尝试从其他线程更新表单控件。我不是专家,但根据我的经验,在某些方面可能会出错。

要清除datagridview,您是否尝试将datagridview的Datasource属性设置为$null,然后再为其分配新值?这就是我通常如何完成我的工作。

答案 1 :(得分:0)

我看到两个问题,第一个需要清除数据源的问题,第二个问题是您在单击按钮并打开运行空间后过早地尝试调用操作。在那里放一个简单的start-sleep,这个问题应该解决。我建议您在睡觉时玩,以获得最快的执行速度。第二个也是一个简单的修复,只需在声明task1之前清除数据源。这对我有用。

$backgroundTask = {
$sync.softwareTable.DataSource = $null
  $task1 = [PowerShell]::Create().AddScript({

        #here I would like to clear all data from a previous execution. But nothing worked.
        $softwareQuery = Get-WMIObject -ComputerName virinfpshd001w  -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
  $handle = $task1.BeginInvoke()
  Start-Sleep -seconds 5
}