Need Dynamic Button Sample

G

Guest

Hi!
I am new to .NET so would appreciate some help.
I am looking for an example of dynamic button creation. There are a lot of
references to it on the postings but I was not able to find examples on how
to actually do it. Can anyone point me to it or maybe post a very basic
example so I can understand the concepts ?

Thanks,
LW
 
W

Wayne

Sorry for the poor formatting, but this should give you the idea. I am only
displaying the buttons on the form, so I didn't need an Arraylist or
anything to keep track of them myself, not sure what you need to do, if you
need to keep track of the buttons I would suggest an ArrayList and add the
new button to the list right after you create it.

private void dynamicButtonClick(object sender, System.EventArgs e)
{
Button button = (Button)sender;
MessageBox.Show(button.Text);
}

private void Form1_Load(object sender, System.EventArgs e)
{
Button curButton; //place holder for the current button
int x = 5; //Keep track of where the current button is to be placed
int y = 5;
for (int i = 0; i < 20; i++)
{
curButton = new Button(); //Create new button
curButton.Click += new EventHandler(dynamicButtonClick); //assign the
click event to the button
curButton.Parent = this; //show the button on the form.
curButton.Location = new System.Drawing.Point(x, y); //set the Buttons
left, top
curButton.Text = i.ToString(); //Set the Text of the button

y += curButton.Height + 5; //Inc the top so the next button appears
below this one.
if (y + curButton.Height > this.ClientRectangle.Height)//Prevent the
buttons from going off the bottom of the form.
{
y = 5;
x += curButton.Width + 5;
}
}
}

--
Thanks
Wayne Sepega
Jacksonville, Fl


"When a man sits with a pretty girl for an hour, it seems like a minute. But
let him sit on a hot stove for a minute and it's longer than any hour.
That's relativity." - Albert Einstein
 
W

Wayne

Do you really need it? everything seemed to work just fine with the example
I posted.

Time to go read what the Controls.add does for you.

Wayne
 
W

Wayne

well went back and looked at what I was doing, if you remove the line:

curButton.Parent = this;


Then the controls don't display, if you check the Controls.Count after
creating all the buttons, it equals 20. So apparently curButton.Parent =
this; adds the buttons to the Controls collection for you.
 
G

Guest

I understand it better and I am actually displaying the buttons and the
callbacks are working as well. Thanks for you help!

LW
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top