Scope UserControl to MainForm

G

Guest

Hello:

What is the correct way to target a method on the MainForm from a
UserControl. For example:

namespace SampleApp
{
public partial class MainForm : Form
{
internal void ShowControl()
{
//code to make a control visible
}

}

public partial class UserControl1 : UserControl
{
private void Button_Click(object sender, System.EventArgs e)
{
//how do I target ShowControl() in the MainForm
}
}
}

Thank you!
 
S

Stoitcho Goutsev \(100\)

Benedict,

You have to have a reference to the form in the user control. You can pass
it as a constructor parameter, set it in a proeprty or have special init
method for this. You can also use FindForm method from the UserControl code
that will give you reference to the form that hosts the control.

Just keep in mind that probably this control may not be hosted in a form
that has ShowControl method.

For example FindForm method will return reference to an object of type Form,
which you need to cast to a type that support this show method. If the cast
is possible (you need to check first) then call the method.

If you use parameter or proeprty to pass the form reference you can strongly
type it to accept only special base type or beter yet an interface the the
forms hosting your user control must implement. This interface will declare
the ShowControl method.

There is another solution that I like better than the previous ones. Instead
of making the control knowing too much about the host. Let the control
control fire an even when ShowControl method needs to be called. The forms
that support this feature need to subscribe for this event and act
accodingly. Thus the control can be used in any form, but only the special
once will react on this event.
 
G

Guest

Stoitcho - this is really helpful, thank you!

Conceptually I understand what needs to be done, I'll look for some samples
on MSDN. Thanks!

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top