Click here to Skip to main content
15,891,738 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
i want to call the form1 button click event in form2 is it possible to call the event click of button?
Posted
Comments
Sergey Alexandrovich Kryukov 23-Nov-11 2:21am    
What is "call event"? There is no such thing.
--SA

First of all, there is no such concept as "call event". You can call and event handler. More exactly, write some method implementing some action to be called on click. Use this method in two places: 1) in the click event handler, 2) where you need to call it without click.

Now, there is a problem how to make this method implemented in one form accessible in another form. Yes, you can make this method internal. (No need to make it public as Rajeev suggested. Never give more access that it is really required.) This will solve the problem, but you also need to pass a reference to one form instance to another one. This is not very good as it breaks isolation of forms and can invite some bugs in bigger applications.

There are more accurate and advanced approaches. Actually, this is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

As you only pass the reference to the form as the reference to the interface, you only pass the access to what is really needed, no more.

—SA
 
Share this answer
 
Do the following things....

Form1
---------
Make the button Click event button1_Click of the Form1 as public.

Form2
-------

C#
Form1 f = new Form1();
 f.button1_Click(sender, e);
 
Share this answer
 
yes you can. but the better approach is..
you create a public method inside Form1, call ButtonClick event from that method. pass your form object to Form2 at initialization of form2 and call this method from object of Form1 on Form2
i.e

C#
partial class Form1
{
 Form1()
 {}
 
 protected Form1_Load(object,EventArgs)
 {
  Form2 frm = new Form2(this);
  frm2.Show();
 }

 protected void Button1_Click(object,EventArgs)
 { //Event Body
 }

 public void CallButton1Click()
 {
   Button1_Click(null,null)
 }
}

class Form2
{
 Form1 frm= null;
 Form2()
 {}
 Form2(Form argForm)
 {
   frm = (Form1) argForm
 }

 protected Form2_Load(object,EventArgs)
 {
   frm.CallButton1Click();
 }
}




it will work for you
 
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