Winforms 在DataGridView(表单内部)中显示表
我试图将一个Winforms 在DataGridView(表单内部)中显示表,winforms,powershell,datagridview,Winforms,Powershell,Datagridview,我试图将一个DataGridView放在表单中。表单和DataGridView显示时没有问题,但表似乎显示不正确 下面是创建表的函数: function tableCreator(){ $script:statusTable = @() $txtPath = $script:targetName Get-Content $txtPath | % { $script:statusTable += New-Object -TypeName PSObject -
DataGridView
放在表单中。表单和DataGridView
显示时没有问题,但表似乎显示不正确
下面是创建表的函数:
function tableCreator(){
$script:statusTable = @()
$txtPath = $script:targetName
Get-Content $txtPath | % {
$script:statusTable += New-Object -TypeName PSObject -Property @{
Computer = "$_";
Connection = "NA";
Status = "NA"
}
}
#$script:statusTableLength = $script:statusTable.Length
}
function runstatusFormFunc {
$reviewprocessForm.Close()
$reviewprocessForm.Visible = $false
tableCreator
testConnection
$script:statusOutput.DataSource = $script:statusTable
$runstatusForm.Add_Shown({$runstatusForm.Activate()})
[void] $runstatusForm.ShowDialog()
}
下面是DataGridView
对象:
$script:statusOutput = New-Object System.Windows.Forms.DataGridView #creating the text box System.Windows.Forms.TextBox
$script:statusOutput.Location = New-Object System.Drawing.Size(20,100) #location of the text box (px) in relation to the primary window's edges (length, height)
$script:statusOutput.Size = New-Object System.Drawing.Size(600,350) #the size in px of the text box (length, height)
$script:statusOutput.ScrollBars = "Vertical" #adding scroll bars if required
$script:statusOutput.DataSource = $script:statusTable
下面是加载表单并将DataSource
设置到表中的函数:
function tableCreator(){
$script:statusTable = @()
$txtPath = $script:targetName
Get-Content $txtPath | % {
$script:statusTable += New-Object -TypeName PSObject -Property @{
Computer = "$_";
Connection = "NA";
Status = "NA"
}
}
#$script:statusTableLength = $script:statusTable.Length
}
function runstatusFormFunc {
$reviewprocessForm.Close()
$reviewprocessForm.Visible = $false
tableCreator
testConnection
$script:statusOutput.DataSource = $script:statusTable
$runstatusForm.Add_Shown({$runstatusForm.Activate()})
[void] $runstatusForm.ShowDialog()
}
最终输出如下所示:
我的问题是
DataGridView
不接受数组作为数据源。它将只接受ArrayList
$Script:statusTable = New-Object System.Collections.ArrayList
而不是
$Script:statusTable = @()
解决问题,DataGridView正确输出对象表这不是问题的解决方案,而是一些一般性建议:尽可能避免使用全局变量。还要避免在循环中附加到数组。尤其要避免同时做这两件事。只需在函数tableCreator
中输出对象,并在调用函数($statusOutput.DataSource=tableCreator
)时收集它们即可。谢谢您的建议!我尽可能地坚持这一点,但是,我在一个单独的函数中修改了DataGridView和StatusTable,因此这不是可能的场景之一。虽然我可能会添加$Script不是$Global作用域。Script:
是Script全局的(而gobal:
是运行时全局的),但它是全局的,没有任何负面影响。