How to dynamically create a button?

  • Thread starter Thread starter Keith Smith
  • Start date Start date
K

Keith Smith

What am I missing? I am trying to dynamically create a button...

Button myButton = new Button();
myButton.Name="ButtonX";
 
Keith said:
What am I missing? I am trying to dynamically create a button...

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

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

Michael
 
Keith Smith said:
What am I missing? I am trying to dynamically create a button...

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

Well, you need to set a location, size, and add it to the control you want
it to appear on.
 
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,
 
Button myButton = new Button();
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)

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]
 
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



Keith Smith said:
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)

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]
 
Back
Top