DerMike
DerMike

Reputation: 16190

What is the Controls's parent for?

I stumbled upon the Control.Parent Property and don't understand what it exists for. When would I want to use or set it?

Upvotes: 0

Views: 50

Answers (3)

ChrisF
ChrisF

Reputation: 137148

You would set it if you wished to move a control from one container to another.

You would use it when traversing the visual tree if you needed to find a group box (say) to hide a group of controls when one is selected.

Upvotes: 1

Oded
Oded

Reputation: 499002

It is a link back to the container of the control.

For example - a button on a form would have this set to the form containing it (assuming no other containers in the chain).

It allows you to add/remove controls dynamically from a container (setting this to null would remove the control from its container, then setting to a different container to add it there).

Upvotes: 2

LarsTech
LarsTech

Reputation: 81610

The parent is the container for the control it is currently in, such as a panel or a form.

Here I can set a property of the parent of the button without caring "who" the parent is:

private void button1_Click(object sender, EventArgs e) {
  if (button1.Parent != null) {
    button1.Parent.BackColor = Color.Red;
  }
}

Upvotes: 1

Related Questions