How to search some control by name?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have one WinForm and 3 buttons on this form.
all buttons are private.

I set the button2's click event to execute the
"Controls.RemoveByKey("button1");".
When I executed the button2's click event, the button1 doesn't exist in
Controls.

My problem is if I want to add button1 into Controls at runtime, but I just
know that button1's name, How to use that name to search and add the button1
to Controls?

*button1's name is "button1".
 
aps-asia,
I set the button2's click event to execute the
"Controls.RemoveByKey("button1");".
When I executed the button2's click event, the button1 doesn't exist in
Controls.

First of all the control doesn't have to have a name specified thus this
methods doesn't work in all the cases. Controls added at design time though
always have names as opposed to controls added at run time, which may have
may not.

Secondly this methods removes controls from the Controls collection only.
That means if you have form and a panel on the form and on the panel theres
is a button, trying to remove the button using reference to the form's
Control's collection won't do because the button is in the panel's control
collection.
My problem is if I want to add button1 into Controls at runtime, but I
just
know that button1's name, How to use that name to search and add the
button1
to Controls?

*button1's name is "button1".

This one I don't quite undestand. Where do you get this button from? If it
is not in the collection where is it then?
If you have it as a field of the form class then you cannot get it by its
name unless you reflect over the class fields. Keep in mind that the VS
designer mames the fields after the control names, but this doesn't have to
be the case. If I create a control from code I can call the fields whatever
I want and the name I can provide or not and it can be different than the
field name.
 
Back
Top