0

I want to dynamically add a click event from form1 to form2.

This is my code in form1:

Form2 frm = new Form2();
string title =(string)listBox1.SelectedItem;
TabPage myTabPage = new TabPage(title);
frm.tabControl1.TabPages.Add(myTabPage);
//create button and it's event
Button button1 = new Button();
button1.Click += new System.EventHandler(button1_Click);
button1.Location = new Point((myTabPage.Width/2)-(button1.Width/2),myTabPage.Height-30);
button1.Text = "Click On Me!";
myTabPage.Controls.Add(button1);
frm.Show();

I get the following error: The name 'button1_Click' does not exist in the current context

Please help.

1
  • 1
    Have yo defined button1_Click any where on new form? If no, you must define it before binding it to any button click event. Commented Apr 16, 2013 at 16:11

2 Answers 2

3

You need to create your button1_Click event handler. At the moment you're assigning the event handler to the button saying "call button1_Click" but you haven't actually created the "button1_Click" method that you want to call.

private void button1_Click(object sender, EventArgs e) 
{
   //code to call when the button is clicked.  
}

Update from comment. You can create an anonymous method.

button1.Click += (s,e) =>
     { 
         //code to call when the button is clicked. 
     };
Sign up to request clarification or add additional context in comments.

1 Comment

yes i know it but i must add it into form2? it not working :(
-1

Could you create the button ahead of time and disable and make invisible until you wanted to use it?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.