Groups | Blog | Home
all groups > c# > october 2005 >

c# : How to dynamically create a button?


Keith Smith
10/12/2005 11:21:54 PM
What am I missing? I am trying to dynamically create a button...

Button myButton = new Button();
myButton.Name="ButtonX";

Daniel O'Connell [C# MVP]
10/12/2005 11:42:24 PM

[quoted text, click to view]

Well, you need to set a location, size, and add it to the control you want
it to appear on.

Michael Kremser
10/13/2005 12:00:00 AM
Keith Smith schrieb:
[quoted text, click to view]

myButton.Location = new Point(8,8);
myButton.Text = "Click me";
this.Controls.Add(myButton); // Adds the button to the form (if you put
this code e.g. in the constructor or better in InitializeComponent)

HTH

Ignacio Machin ( .NET/ C# MVP )
10/13/2005 8:33:17 AM
Hi,


In addition to the other post you better take a look at the code generated
by the designer. You will learn few things.

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation



[quoted text, click to view]

Keith Smith
10/13/2005 9:44:30 AM
[quoted text, click to view]

Thanks alot, Michael!

I forgot to mention this earlier.... How can I make an "array" of these
buttons as well? Would it be sometime like this...?

Button myButton = new array[10]

Ignacio Machin ( .NET/ C# MVP )
10/13/2005 11:10:16 AM
Hi,

Yes, that's the way of doing

But note that unless you need to change properties ( visible, position,
etc) of them during the course of the execution you do not need hold a
reference to them.
Usually what you do is create event handlers ( like Click ) and you interact
with them this way.

Also note that you can use Controls.AddRange instead of Controls.Add , also
a good idea to wrap it in a Suspend/ResumeLayout calls

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation



[quoted text, click to view]

AddThis Social Bookmark Button