Page 1 of 1

dynamically reference objects on form

Posted: Wed Apr 02, 2014 7:56 pm
by boyddt_co
I have a number of text boxes and labels on my form that need to be updated based on some database queries. If I return a 1 and a 2 can I create a variable that would reference label $M1D2?

Such as
$x = 1
$i = 2
$Label = "M+$x+D+$i"
$Label.Text = "Finished"

Re: dynamically reference objects on form

Posted: Wed Apr 02, 2014 8:40 pm
by jvierra
What you are asking is can you compute the controls.

If a control is named 'R2D2'

$label=$form1.Controls['R2D2']
$label.Text='This is R2D2'

Re: dynamically reference objects on form

Posted: Thu Apr 03, 2014 2:47 pm
by boyddt_co
Not exactly. I would still need to know the control names what I want to do is to build the control names from variables. Given your suggestion, and I believe that it might be the only option, I would need code like this

$x = 1
$i = 2

switch ($x)
{
1 {
switch ($i)
{
1{ $label = $form1.Controls('m1d1') }
2{ $label = $form1.Controls('m1d2') }
3{ $label = $form1.Controls('m1d3') }
}
2 {
switch ($i)
{
1{ $label = $form1.Controls('m2d1') }
2{ $label = $form1.Controls('m2d2') }
3{ $label = $form1.Controls('m2d3') }
}
}
}

I on the other hand would just like to be able to have code like this

$label = $form1.Controls('m$xd$i')
$label.text = 'finished'

Re: dynamically reference objects on form

Posted: Thu Apr 03, 2014 3:19 pm
by jvierra
You are not really thinking this through.
PowerShell Code
Double-click the code block to select all.
$x=1
$i=2

$labelName = 'M'+$x+'D'+$i
$form1Controls[$labelName].Text='Finished'
That finds a label with the calculated names and assigns its text value. That is what you are asking. YOu need to be sure to name all of your controls.

Re: dynamically reference objects on form

Posted: Thu Apr 03, 2014 7:19 pm
by boyddt_co
Jvierra, thank you for the help. I'll play with it tonight. As far as thinking it through, I have a small brain so I got as far as I could. :lol:

Thanx again,

David

Re: dynamically reference objects on form

Posted: Thu Apr 03, 2014 7:35 pm
by jvierra
The point is that controls are identified by name on the controls collection because it is a "keyed" collection or what is sometimes called a dictionary. This makes it convenient for associating a control with some aspect of data or a program where we can extract or calculate a name.

We can also use this mechanism as a convenient way of extracting the data from a form after is has been closed. That is the point of the "DialogResult" It tells us whether the data in the form should be extracted or ignored.