Hi folks
I am trying to think through how it would be possible to dynamically generate events for dynamically generated controls.
For example, I would like to have an XML file which has the different options I want to dynamically load into an options page. I have managed to do this and create a Label and a Textbox, I can take input and everything is good. Suppose however, 1 of my options is for a file path. I want to dynamically create a Label and a Textbox, but also a button next to the Text Box which is linked to an FolderBrowserDialog control. The Button needs to have a Click event, that then points to the FolderBrowserDialog and has the necessary code for what to do next.
Is this something that is possible, if so, can someone point me in the right direction for how to approach this, perhaps a blog post or tutorial? Or, If I am getting too carried away and things like this should be statically defined, please let me know!
Thanks!
Is it possible to dynamically generate event code?
Forum rules
Do not post any licensing information in this forum.
Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Do not post any licensing information in this forum.
Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Re: Is it possible to dynamically generate event code?
Here is a partial example from another project:
Code: Select all
[xml]$xml = @'
<?xml version="1.0"?>
<Form Name="testForm" Text="Test Generated Form" StartPosition="CenterScreen" Size="600,400">
<Events>
<Event Name="Closing">
<![CDATA[
Write-Host 'I am closing now' -Fore Green
]]>
</Event>
</Events>
<Controls>
<Control Type="Button" Name="closeutton" Location="10,10" Text="Close" DialogResult="Ok"/>
</Controls>
</Form>
'@
#create the form
$hash = @{}
$xml.Form.Attributes |
ForEach-Object{
$hash.Add($_.Name,$_.Value)
}
$form = [System.Windows.Forms.Form]$hash
# create the controls and add to the form
$xml.Form.Controls.Control |
ForEach-Object{
$button = $_
Switch ($_.Type){
Button {
$hash = @{}
$button.Attributes
$button.Attributes | ?{$_.Name -ne 'Type'} |
ForEach-Object{
$hash.Add($_.Name, $_.Value)
}
$c = [System.Windows.Forms.Button]$hash
$form.Controls.Add($c)
}
Label {}
TextBox {}
}
}
#add the events (you have to code a loop to find and do all control events
$xml.Form.Events.Event |
ForEach-Object{
$script = [scriptblock]::Create($_.'#cdata-section')
$form.add_closing($script)
}
$form.ShowDialog()
Re: Is it possible to dynamically generate event code?
That's awesome, thank you, I will try it out today!