How to get access to a control created at runtime

  • Thread starter Thread starter Andrei Pociu
  • Start date Start date
A

Andrei Pociu

Inside a method some controls are created at runtime.
I added an event handler to one of these controls:

tracker.Scroll += new System.EventHandler(this.tracker_Scroll);

So in the event handler I used unboxing to get access to the value of the
TrackBar:

private void tracker_Scroll(object sender, System.EventArgs e)
{
TrackBar currTrack = (TrackBar)sender;
MessageBox.Show(currTrack.Value.ToString());
}

It works fine, but inside the event handler I also want to change the
property of another control created at runtime (set a TextBox to the value
of the TrackBar).
My question is, of course, how do I do that, how do I get access to the
TextBox created at runtime?

Thank you.
 
At design time, if you know you will eventually create the Textbox, you can
create its reference. At compile time it will be null. In you eventhandler,
before using it, check to make sure your control was actually created (and
assigned to your Textbox reference).

If this doesn't apply, you'll have to know something (i.e. its name) about
the control. So when the Textbox is created, add it to the Form Controll
collection. In your eventhandler, search the Controls collection for the
Textbox with the matching name.

good luck
kevin aubuchon
 
Telmo, I have tried that, unfortunately it doesn't seem to work.

Kevin, I did this (creating the TextBox reference) some time ago when I had
the same problem and it works.
Probably I'll end up doing it again, but there are lots of controls created
at runtime in different methods, so I thought that there might be a better
solution than creating a reference to all of them.

Thank you both.
 
Yes, the control is in a panel... that's why the control couldn't be added
to the Controls collection.
I'll try this, thanks.
 
What do you mean by "it doesn't seem to work" (regarding the Controls
collection)?
If the control was added to the Controls collection, it'll be there. The
'problem' is if you didn't add the control straight on the form but on
one of the panels/tabpages/etc. on it, in which case you should traverse
the container-control relationships along the way.
 
Back
Top