Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

c# - How can I get all controls from a Form Including controls in any container?

I need, for example, a way to disable all buttons in a form or validate all textboxes' data. Any ideas? Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest option may be to cascade:

public static void SetEnabled(Control control, bool enabled) {
    control.Enabled = enabled;
    foreach(Control child in control.Controls) {
        SetEnabled(child, enabled);
    }
}

or similar; you could of course pass a delegate to make it fairly generic:

public static void ApplyAll(Control control, Action<Control> action) {
    action(control);
    foreach(Control child in control.Controls) {
        ApplyAll(child, action);
    }
}

then things like:

ApplyAll(this, c => c.Validate());

ApplyAll(this, c => {c.Enabled = false; });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...