Oscar Cheung
Oscar Cheung

Reputation: 133

Add specific Button with Control constructor?

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.

Upvotes: 1

Views: 545

Answers (2)

Rafal Spacjer
Rafal Spacjer

Reputation: 4918

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);

Upvotes: 0

escargot agile
escargot agile

Reputation: 22389

You can use property initializers when constructing an object:

Controls.Add(
    new Button    
    {
       Text = "Press me",
       Left = 400,
       // initialize any properties you wish
    });

Upvotes: 1

Related Questions