I used PowerShell to create a Windows Form with a TextBox field and a Button object. When I clicked the Button it will open the OpenFileDialog for user to select a file. How do I return the selected filename from OpenFileDialog and display in the TextBox field ?
Sample Code as follows:
$Filename = New-Object TextBox
$Filename.Location = New-Object System.Drawing.Point(230, 80)
$Filename.Size = New-Object System.Drawing.Size(400, 80)
$Filename.Font = New-Object System.Drawing.Font("Calibri", 12, [FontStyle]::Bold)
# $Filename.Text = $OpenFileDialog.FileName
$BrowseButton = New-Object Button
$BrowseButton.Location = New-Object System.Drawing.Point(650, 80)
$BrowseButton.Size = New-Object System.Drawing.Size(100, 30)
$BrowseButton.Font = New-Object System.Drawing.Font("Calibri", 12, [FontStyle]::Bold)
$BrowseButton.Text = "Browse..."
$BrowseButton.Add_Click($BrowseButton_Click)
$BrowseButton_Click =
{
$OpenFileDialog = New-Object OpenFileDialog
$OpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx)|*.xls;*.xlsx|All files (*.*)|*.*"
$OpenFileDialog.FilterIndex = 2
$OpenFileDialog.RestoreDirectory = $true
if ($OpenFileDialog.ShowDialog() -eq [DialogResult]::OK)
{
# Do something to return the $OpenFileDialog.FileName to the TextBox field
}
}
The line you have commented:
Should be what happens as a result of your
ifcondition:In order to update the
.Textproperty of yourTextBox.It's also worth noting that the
$BrowseButton_ClickScriptBlock has to be defined before being added:$BrowseButton.Add_Click($BrowseButton_Click). PowerShell interprets code line-by-line and and as you have right now you will be trying to add$nullto your.Clickevent.In summary: