Click here to Skip to main content
15,885,870 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a button1 in form1 and I want if I press button1 it create button2 in form1 and if you press button2 it display a message.
how can I do that ?
Posted
Comments
Abdul Quader Mamun 16-Feb-11 5:06am    
Where is your code?

Easy:
C#
private void MyExistingButton_Click(object sender, EventArgs e)
    {
    Button myNewButton = new Button();
    myNewButton.Text = "ClickMe";
    myNewButton.Location = new Point((Width - myNewButton.Width) / 2, (Height - myNewButton.Height) / 2);
    myNewButton.Click += new EventHandler(myNewButton_Click);
    Controls.Add(myNewButton);
    }
void myNewButton_Click(object sender, EventArgs e)
    {
    MessageBox.Show("Hello World!");
    }
 
Share this answer
 
Comments
JF2015 16-Feb-11 5:57am    
Simple and correct.
Albin Abel 16-Feb-11 6:12am    
this is best answer, my 5
create button in run time and add what u want as event
like this:
..it's click event of button1 and in method must have argument
object x,eventargs xx
C#
private void button1_Click(object sender, EventArgs e)
        {
            Button button2 = new Button();
            button2.Location = new System.Drawing.Point(100, 60);
            button2.Name = "but";
            button2.Size = new System.Drawing.Size(75, 23);
            //button2.TabIndex = 0;
            button2.Text = "button1";
            button2.UseVisualStyleBackColor = true;
            button2.Click+=new EventHandler(ok);
            this.Controls.Add(button2);
        }
        public void ok(object sender,EventArgs e)
        {
            MessageBox.Show("mohamed");
        }
 
Share this answer
 
Hi ZPS769,

You can drag and drop button 2 in your form and set its visibility to false.

On pressing button1 :

private void button1_Click(object sender, EventArgs e)
{
    button2.Visible = true;
}


and on Pressing button2 :

private void button2_Click(object sender, EventArgs e)
{
    MessageBox.Show("Hello world");
}


I hope this help
:)
 
Share this answer
 
You need to dynamically create a new button on Button1 click.
Then add that new button to controls in Form and set locations.
Also, you need to assign an event handler for new button click.
Then, you can do whatever while handling that event.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900