Reputation: 2661
I have 2 winforms
called AppNamespace.MYForm
and AnotherNamespace.AnotherForm
.
They both have a button.
When the user click on the button of AnotherNamespace.AnotherForm
I would like to perform a click on the button located on AppNamespace.MYForm
.
However, there is a constriant that AnotherNamespace
cannot use AppNamespace
.
This prevents me from doing :
AppNamespace.MYForm firstForm = new AppNamespace.MYForm();
firstForm.button.PerformClick();
Any ideas?
Upvotes: 0
Views: 147
Reputation: 54433
Either make the Button
on the second form public
by editing the Form2.Designer.cs:
public System.Windows.Forms.Button button1;
And register its Click
with the 1st Form:
private void Form1_Load(object sender, EventArgs e)
{
// or whatever you do to create the 2nd form..
AnotherNamespace.Form2 F2 = new AnotherNamespace.Form2();
F2.Show();
// register the click:
F2.button1.Click += button2_Click;
}
Or create a Property
in the 2nd form:
public Button myButton { get; set; }
And set it to the Button
:
public Form2()
{
InitializeComponent();
myButton = button1;
}
Now you can register its Click
like this:
F2.myButton.Click += button2_Click;
Upvotes: 0
Reputation: 6849
Manually executing event of any control is a bad practice. Create separate method and execute it instead.
You can create interface then implement it to both forms. The interface should contains a method PerformClick
.
public Interface IMyInterface
{
void PerformClick(string _module);
}
public class Form1 : IMyInterface
{
public void IMyInterface.PerformClick(string _module)
{
//CODE HERE
if (Application.OpenForms["Form2"] != null && _module != "Form2")
((IMyInterface)Application.OpenForms["Form2"]).PerformClick(_module);
}
private void button1_Click(object sender, EventArgs e)
{
this.PerformClick(this.Name);
}
}
public class Form2 : IMyInterface
{
public void IMyInterface.PerformClick()
{
//CODE HERE
if (Application.OpenForms["Form1"] != null && _module != "Form1")
((IMyInterface)Application.OpenForms["Form1"]).PerformClick(_module);
}
private void button1_Click(object sender, EventArgs e)
{
this.PerformClick(this.Name);
}
}
Upvotes: 0
Reputation: 11
Separate the button click code in a helper class/another namespace and call it in button click.
You can use the method in any namespace by calling helper namespace and method.
Upvotes: 1