1

I know this might a simple question, but is there a way to add a Button (or other controls) to a Windows Form in just one line? Something like:

// Control constructor: new Control(string text, int left, int top, int x, int y)

Control.Add(new Control("Press me!", 100, 100, 40, 40) as Button);

since I want to use the Control constructor to define both the button's size and position on the form.

Thanks in advance.

2 Answers 2

1

You can use property initializers when constructing an object:

Controls.Add(
    new Button    
    {
       Text = "Press me",
       Left = 400,
       // initialize any properties you wish
    });
Sign up to request clarification or add additional context in comments.

1 Comment

You can even do the whole thing in the initializer. Instead of wrapping a Controls.Add around the whole thing, just add another property assignment to the initializer: Parent = this. It looks a little odd (a new expression not being assigned to anything) but it works.
0

You can do this, but first you have to create Button class instance and then add it to the Controls collection. For example like this:

var button = new Button();
button.Name = "btnTest";
button.Size = new Size(10,10);

and then:

Controls.Add(button);

2 Comments

Thanks for the answer, though I know how to do that, I just want to avoid using lots of lines / methods to add a button. Thanks though.
Ok, I understand. Ilya Kogan has shown a bit smaller version :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.