Home > Software design >  clearing a textbox which is in a function
clearing a textbox which is in a function

Time:01-18

i have a function that create a textbox (info box) and can be called from other functions or from buttons.

function InfoBox ($x,$y,$text){
    $TextboxInfoBox = New-Object System.Windows.Forms.TextBox
    $TextboxInfoBox.Location = New-Object System.Drawing.Size($x,$y)
    $TextboxInfoBox.Size = New-Object System.Drawing.Size(200,800)
#   Readonly Textbox.
    $TextboxInfoBox.Enabled = $true
    $TextboxInfoBox.Text = $text
    $TabPanelButtons.Controls.Add($TextboxInfoBox)
}

After i called the textbox once, i am not able to overwrite it with another info message. the first time i call with all the parameters ($x, $y & $text).

Infobox -x '100' -y '150' -text 'This is the first message'

The second time i only want to give another text. How can i clear the textbox and give only a new text like:

Infobox -text "This is the second message"

Any Ideas?

CodePudding user response:

As commenter wrote, the function has to output the TextBox object so you can reference it later to change the text:

function InfoBox ($x,$y,$text){
    $TextboxInfoBox = New-Object System.Windows.Forms.TextBox
    $TextboxInfoBox.Location = New-Object System.Drawing.Size($x,$y)
    $TextboxInfoBox.Size = New-Object System.Drawing.Size(200,800)
#   Readonly Textbox.
    $TextboxInfoBox.Enabled = $true
    $TextboxInfoBox.Text = $text
    $TabPanelButtons.Controls.Add($TextboxInfoBox)

    $TextboxInfoBox  # Output
}

Contrary to most other programming languages, in PowerShell you normally don't need to use the return statement, except for early return from a function. Simply referring to a variable by name on its own line will output its value from the function.

Now you can store the output in a variable and change the text:

$box = Infobox -x 100 -y 150 -text 'This is the first message'

$box.Text = 'This is the second message'
  •  Tags:  
  • Related