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.
You can use property initializers when constructing an object:
Controls.Add(
new Button
{
Text = "Press me",
Left = 400,
// initialize any properties you wish
});
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);
精彩评论