TheTalentedDrAl
TheTalentedDrAl

Reputation: 85

C# adding textbox from nested classes

I've got a form, which on load instantiates another class (boxMaker) which in turn creates another (boxObj). I want the boxObj to be able to make a textbox which appears on my form.

2 questions:

It doesn't show my textbox unless I use form.controls.add(textBox); - is that correct?

In order for that to work, I have to pass the original form to each of the classes in turn: Pseudo-code:

new boxMaker(this)

boxMaker creator:

public boxMaker (Form form)
new boxObj(form)

boxObj creator:

public boxObj (Form form)
new textbox
form.controls.add(textbox)

It feels REALLY clunky to have to keep passing the original object all the way down the chain:

Is there a neater way to do it?

Upvotes: 0

Views: 48

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You could make the BoxMaker return a TextBox, and let the Form handle adding it to the Control list instead of passing the original Form around:

public class BoxMaker
{
    public TextBox CreateTextBox()
    {
        TextBox textBox = new TextBox();
        // Do Stuff
        return textBox;
    }
}

And use it inside your Form like so:

public class Form1
{
    public void SomeEventHandler(object sender, EventArgs e)
    {
        BoxMaker maker = new BoxMaker;
        TextBox makerMadeTextBox = maker.CreateTextBox();
        this.Controls.Add(makerMadeTextBox);
    }
}

Upvotes: 1

Related Questions