【问题标题】:Need to create, use and store dynamic object names in Powershell需要在 Powershell 中创建、使用和存储动态对象名称
【发布时间】:2018-12-10 03:53:45
【问题描述】:

我正在加载一个文本文件并循环遍历每一行,并尝试以 powershell 形式打印一个复选框。但是,按照下面的方式,所有复选框都具有相同的变量/对象名称,这使得无法区分它们。

我需要一种方法来通过 $checkbox(文本文件中的行数,可以更改)动态创建 $checkbox0,并将它们填写在下面,并存储名称,这样我可以验证它们是否被稍后单击

$pFile = Get-Content "C:\results.txt"
$rowCounter = 0
foreach($line in $pFile){
    $checkbox = New-Object System.Windows.Forms.CheckBox
    $checkbox.UseVisualStyleBackColor = $True
    $System_Drawing_Size = New-Object System.Drawing.Size
    $checkbox.AutoSize = "true"
    $checkbox.TabIndex = $rowCounter
    $checkbox.Text = $line
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 25
    $yValue = (20 * $rowCounter)
    $System_Drawing_Point.Y = $yValue
    $checkbox.Location = $System_Drawing_Point
    $checkbox.DataBindings.DefaultDataSourceUpdateMode = 0
    $Form1.Controls.Add($checkbox)
    $rowCounter = $rowCounter + 1
}

【问题讨论】:

  • 有什么特殊原因不能简单地使用数组而不是单独命名的编号变量吗?
  • 想详细说明一下?我不知道文本文件会有多少行,所以我不知道我需要多少变量。
  • 您认为您可以通过$checkbox0 完成哪些您无法通过$checkbox[0] 完成的操作?

标签: winforms powershell object checkbox dynamic


【解决方案1】:

Control 具有Name 属性,它是一个字符串。为控件分配一个唯一的名称,稍后您可以在父控件的Controls 集合中找到它。

另外,如果您正确地为控件的事件分配了事件处理程序,您可以在事件处理程序的 sender 参数中接收该控件。

在下面的代码中,我创建了一个CheckBox 控件列表并为它们处理CheckedChanged 事件:

Add-Type -AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$flp = New-Object System.Windows.Forms.FlowLayoutPanel
$form.Controls.Add($flp)
#Let's say you read the following values from file
$array = ("Lorem", "Ipsum", "Dolor") 
$i = 0
$array | % {
    $checkBox = New-Object System.Windows.Forms.CheckBox
    $checkBox.Text = $_
    $checkBox.Name = "checkBox_$i"
    $flp.Controls.Add($checkBox)
    $checkBox.Add_CheckedChanged({
        $index = $flp.Controls.IndexOf($this)
        $name = $this.Name
        $text = $this.Text
        $value = $this.Checked
        [System.Windows.Forms.MessageBox]::Show("Index: $index" +"`n" +
            "Name: $name" + "`n" +
            "Text: $text" + "`n" +
            "Value: $value" + "`n")
    })
    $i++
}
$form.ShowDialog()
$form.Dispose()

【讨论】:

    猜你喜欢
    • 2012-07-09
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多