I use a ComboBox
to get a directory. I need to update the directory by using the Button.Click
event.
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = '400,400'
$Form.TopMost = $false
$ComboBox1 = New-Object system.Windows.Forms.ComboBox
$ComboBox1.width = 100
$ComboBox1.height = 20
$ComboBox1.location = New-Object System.Drawing.Point(36,60)
$ComboBox1.Font = 'Microsoft Sans Serif,10'
$list = @(Get-ChildItem -Directory ".\").Name
foreach ($lst in $list) {
$ComboBox1.Items.Add($lst)
}
$Button1 = New-Object system.Windows.Forms.Button
$Button1.text = "update"
$Button1.width = 60
$Button1.height = 30
$Button1.location = New-Object System.Drawing.Point(182,60)
$Button1.Font = 'Microsoft Sans Serif,10'
$Button1.Add_Click({
})
$Form.controls.AddRange(@($ComboBox1,$Button1))
$Form.ShowDialog()
You are populating the ComboBox
with this...
$list = @(Get-ChildItem -Directory ".\").Name
foreach ($lst in $list) {
$ComboBox1.Items.Add($lst)
}
It sounds like you want clicking the Button
to simply do that again so the ComboBox
will contain an up-to-date list of directories. In that case your Click
event handler should be created like this...
$Button1.Add_Click({
# Remove all items from the ComboBox
$ComboBox1.Items.Clear()
# Repopulate the ComboBox, just like when it was created
$list = @(Get-ChildItem -Directory ".\").Name
foreach ($lst in $list) {
$ComboBox1.Items.Add($lst)
}
})
Clear()
is called first so you don't end up with duplicate directory items.
By the way, you can simplify this...
$list = @(Get-ChildItem -Directory ".\").Name
foreach ($lst in $list) {
$ComboBox1.Items.Add($lst)
}
...to this...
$list = @(Get-ChildItem -Directory ".\").Name
$ComboBox1.Items.AddRange($list)
...or even this...
$ComboBox1.Items.AddRange(@(Get-ChildItem -Directory ".\").Name)