How to get access to a control created at runtime

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.
 
T

Telmo Sampaio

Have you tried playing with the Controls collection of your form?

Telmo Sampaio
 
K

Kevin Aubuchon

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
 
A

Andrei Pociu

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.
 
A

Andrei Pociu

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.
 
U

Uri Dor

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top