Reputation: 163
I'm trying to create 4 buttons on my form when I click on button1
, but the buttons don’t show up. Why not?
private void button1_Click(object sender, EventArgs e)
{
Button[] b = new Button[4];
for (int i=0; i < 4; i++)
{
b[i] = new Button();
b[i].Name = "button" + i;
b[i].Location = new Point(43, 39 + 10 * i);
b[i].Size = new Size(158, 48);
}
}
Upvotes: 0
Views: 156
Reputation: 1259
Try this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace winFormButtons
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Button[] b = new Button[4];
for (int i = 0; i < 4; i++)
{
b[i] = new Button();
b[i].Name = "button" + i;
b[i].Location = new Point(43, 39 + 10 * i);
b[i].Size = new Size(158, 48);
b[i].Click += new EventHandler(OnClick);
this.Controls.Add(b[i]);
}
}
public void OnClick(object sender, EventArgs e)
{
MessageBox.Show("Hello Handler:" + ((Button)sender).Name);
}
}
}
Upvotes: 1
Reputation: 12439
Create a Panel
on your form. and add this line in your code
panel1.Controls.Add(b[i])
Upvotes: 0
Reputation: 45083
All you do is create an array of buttons, and assign buttons at indices. Your form knows nothing of these buttons, they could be an array of integers or anything for all that matters at this point. You will need to put them in the form's container:
Controls.Add(b[i]);
Now your form will take ownership of them, managing disposal when the container is disposed.
Upvotes: 1
Reputation: 27584
You have only created them, but you also need to add them to your form with: this.Controls.Add(b[i]);
private void button1_Click(object sender, EventArgs e)
{
Button[] b = new Button[4];
for (int i=0; i < 4; i++)
{
b[i] = new Button();
b[i].Name = "button" + i;
b[i].Location = new Point(43, 39 + 10 * i);
b[i].Size = new Size(158, 48);
this.Controls.Add(b[i]);
}
}
Upvotes: 5