weeman
weeman

Reputation: 1

Creating a dynamic button

I am trying to creat a dynamic button in a my application. So basically I have this code but when I run it I don’t see the bottom in the other form . The panel is empty. I create the bottom on a button click in a first form then it has to show the button in the second form’s panel.

private void btnsend_Click(object sender, EventArgs e)
{
    this.Hide();
    Form wrr = new Interface();
    wrr.Show();
    createnutton();
}

int i = 0;
int x = 0;

private void createnutton()
{
    Button btn = new Button();
    btn.Location = new Point(3 + i, 14 + x);
    btn.BackColor = System.Drawing.Color.Red;
    btn.ForeColor = System.Drawing.Color.Yellow;
    btn.Text = "Tabel" + libtno.Text;
    btn.Click += new EventHandler(btn_Click);
    panel3.Controls.Add(btn);
    i += 10;
    x += 10;
}

void btn_Click(object sender,EventArgs e)
{
    MessageBox.Show("me");
}

Upvotes: 0

Views: 189

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

You need a reference to the instance of Interface that you created. Pass wrr to your createnutton function. For this to work, you have to change the MODIFIERS property of panel3 to PUBLIC. You also can't reference the Form with the generic Form type. It has to be of that specific Form type, which is Interface (a horrible name by the way, since interface has different meaning in C#):

private void btnsend_Click(object sender, EventArgs e)
{
    this.Hide();
    Interface wrr = new Interface();
    wrr.Show();
    createnutton(wrr); // <-- pass "wrr" to the function
}

int i = 0;
int x = 0;

private void createnutton(Interface frmInterface) // <-- parameter added
{
    Button btn = new Button();
    btn.Location = new Point(3 + i, 14 + x);
    btn.BackColor = System.Drawing.Color.Red;
    btn.ForeColor = System.Drawing.Color.Yellow;
    btn.Text = "Tabel" + libtno.Text;
    btn.Click += new EventHandler(btn_Click);
    frmInterface.panel3.Controls.Add(btn); // <-- use the passed in form
    i += 10;
    x += 10;
}

BUT...this seems like a horrible design. I wouldn't do this if I were personally writing from the ground up.

Upvotes: 0

Yuvraj Mule
Yuvraj Mule

Reputation: 450

You have to set one more property "Visible=true" for your Button.

Upvotes: 1

Related Questions