Hello,
I’m trying to build a module of functions relating to building forms. This might already have been done but its a good way to learn and I’ve hit a snag. The code below should generate a form with a text box and two comboboxes. This works fine except for the fact that the combo box generated by the function fails to return any data compare to the other one which seems to work fine!
Can anyone see where I’ve gone wrong? I’m assuming that its something in the Combobox function.
$Name = ""
$Office = ""
$Office2 = ""
# This Function Generates a ComboBox
function Add-TPN2ComboBox ($x=120, $y=10, $width=100, $height=20, $values, $text, $Outputvariable) {
$ComboBox = new-object System.Windows.Forms.ComboBox
$ComboBox.Location = new-object System.Drawing.Size($x,$y)
$ComboBox.Size = new-object System.Drawing.Size($width,$height)
$ComboBox.Text = $text
ForEach ($value in $values) {
$ComboBox.Items.Add($value)
}
$Form.Controls.Add($ComboBox)
}
# This Function Generates a label
function Add-TPN2Label ($text="label text", $x=10, $y=10, $width=100, $height=20) {
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Text = "$text"
$objLabel.Location = New-Object System.Drawing.Size($x,$y)
$objLabel.Size = New-Object System.Drawing.Size($width,$height)
$Form.Controls.Add($objLabel)
}
function Add-TPNButton($text="OK", $x=240, $y=10, $width=75, $height=20, $action){
$objButton = New-Object System.Windows.Forms.Button
$objButton.Location = New-Object System.Drawing.Size($x,$y)
$objButton.Size = New-Object System.Drawing.Size($width,$height)
$objButton.Text = "$text"
$objButton.Add_Click($Action)
$Form.Controls.Add($objButton)
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.width = 450
$Form.height = 500
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $True
$y = 10 #The initial margin from the top, 10 px is the default value if not specified.
$Values = @("Bristol", "Manchester", "Burton", "London", "Bangkok")
Add-TPN2Label -text "Firstname" -y $y
$FirstName = Add-TPNTextbox -y $y -text "John"
$y = $y + 30
#Add an Office drop-down box to the form.
Add-TPN2Label -text "Office:" -y $y #Add a label to the Office dropdown.
$ComboBoxOffice = new-object System.Windows.Forms.ComboBox
$ComboBoxOffice.Location = new-object System.Drawing.Size(120,$y)
$ComboBoxOffice.Size = new-object System.Drawing.Size(130,30)
ForEach ($Value in $Values) {
$ComboBoxOffice.Items.Add($Value)
}
$Form.Controls.Add($ComboBoxOffice)
$y = $y + 30
Add-TPN2Label -text "Office2" -y $y
$ComboBoxOffice2 = Add-TPN2Combobox -y $y -values $Values -width 130
$y = $y + 30
Add-TPNButton -Action {$this.Parent.Close()} -y $y -text "OK"
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
write-host "Name: " $Firstname.Text
write-host "Office: " $ComboBoxOffice.SelectedItem
write-host "Office2: " $ComboBoxOffice2.SelectedItem