Home > database >  Powershell winforms reference parent in child form
Powershell winforms reference parent in child form

Time:04-12

I'm having a difficulty referencing parent form in child form. I've mocked up a little snippet for this purpose. I know that I have to assign parent property to child form, but I have not had success so far. Please advise

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

#### PARENT FORM

$date = New-Object System.Windows.Forms.Form
$date.Text = 'Date'
$date.Size = New-Object System.Drawing.Size @(243,230)
$date.StartPosition = 'CenterScreen'

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'OK'
$OKbutton.Add_Click({$kibel.showdialog()})
$date.Controls.Add($OKButton)

$date_label = New-Object System.Windows.Forms.Label
$date_label.Location = New-Object System.Drawing.Point(75,70)
$date_label.Size = New-Object System.Drawing.Size(75,23)
$date_label.BorderStyle = 'Fixed3D'
$date_label.Add_Click({$kibel.showdialog()})
$date.Controls.Add($date_label)

##### CHILD FORM

$kibel = New-Object System.Windows.Forms.Form
$kibel.Text = 'Date'
$kibel.Size = New-Object System.Drawing.Size @(243,230)
$kibel.StartPosition = 'CenterScreen'

$kibel_texbox= New-Object System.Windows.Forms.TextBox
$kibel_texbox.Location = New-Object System.Drawing.Point(75,70)
$kibel_texbox.Size = New-Object System.Drawing.Size(75,23)
$kibel.Controls.Add($kibel_texbox)

$kibel_button = New-Object System.Windows.Forms.Button
$kibel_button.Location = New-Object System.Drawing.Point(75,120)
$kibel_button.Size = New-Object System.Drawing.Size(75,23)
$kibel_button.Text = 'KIBEL'
$kibel_button.Add_Click({$kibel.Parent.Controls['date_label'].Text ='done'})
$kibel.Controls.Add($kibel_button)



$date.ShowDialog()

As it is now I am getting Cannot index into a null array error

CodePudding user response:

Two problems you need to address:

  • You need to use the Owner property to designate the parent/owning form
  • You haven't assigned a name to the $date_label control, so Controls['date_label'] won't resolve to anything

The first problem can be addressed by assigning the parent form instance to the Owner property on the child form:

$kibel = New-Object System.Windows.Forms.Form
$kibel.Text = 'Date'
$kibel.Size = New-Object System.Drawing.Size @(243,230)
$kibel.StartPosition = 'CenterScreen'
# designate owning form
$kibel.Owner = $date

Then, to name the label, add this after defining $date_label:

$date_label.Name = 'date_label'

And finally, to correctly resolve the control via the parent form, change the Click event handler as follows:

$kibel_button.Add_Click({$kibel.Owner.Controls['date_label'].Text ='done'})
  • Related