Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell default dropdown value

I have a script where user selects choice from drop-down. But if a user doesn't select anything, I get error. How do I set a default value that is returned, even if user doesn't enter value.

Here is script

########################

# Edit This item to change the DropDown Values

[array]$DropDownArray = "c", "d", "share"

# This Function Returns the Selected Value and Closes the Form

function Return-DropDown {
 $script:Choice = $DropDown.SelectedItem.ToString()
 $Form.Close()
}

function selectShare{
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")


    $Form = New-Object System.Windows.Forms.Form

    $Form.width = 300
    $Form.height = 150
    $Form.Text = ”DropDown”

    $DropDown = new-object System.Windows.Forms.ComboBox
    $DropDown.Location = new-object System.Drawing.Size(100,10)
    $DropDown.Size = new-object System.Drawing.Size(130,30)

    ForEach ($Item in $DropDownArray) {
     [void] $DropDown.Items.Add($Item)
    }

    $Form.Controls.Add($DropDown)

    $DropDownLabel = new-object System.Windows.Forms.Label
    $DropDownLabel.Location = new-object System.Drawing.Size(10,10) 
    $DropDownLabel.size = new-object System.Drawing.Size(100,40) 
    $DropDownLabel.Text = "Select shared folder to deploy SEP"
    $Form.Controls.Add($DropDownLabel)

    $Button = new-object System.Windows.Forms.Button
    $Button.Location = new-object System.Drawing.Size(100,50)
    $Button.Size = new-object System.Drawing.Size(100,20)
    $Button.Text = "Select an Item"
    $Button.Add_Click({Return-DropDown})
    $form.Controls.Add($Button)

    $Form.Add_Shown({$Form.Activate()})
    [void] $Form.ShowDialog()


    return $script:choice
}

$share = selectShare
write-host $share

And here is the error if user doesn't select from drop-down

You cannot call a method on a null-valued expression.
At D:\Script\comp.ps1:10 char:2
+  $script:Choice = $DropDown.SelectedItem.ToString()
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
like image 904
Glowie Avatar asked Dec 16 '25 18:12

Glowie


1 Answers

Why not just do:

$DropDown.SelectedItem = $DropDown.Items[0]

before you show the form? Or set it to = whatever your default item is.

Edit: Or better yet, set up a value checking function and call that when they click OK to make sure all your fields have valid values.

like image 157
TheMadTechnician Avatar answered Dec 20 '25 03:12

TheMadTechnician



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!