Yasston
Yasston

Reputation: 35

Call a user control method on a UserControl object

I have a user control class that is derived from UserControl

[ComVisible(true)]
public class MyUserControl : UserControl

it contains a method I called Initialize() : public void Initialize() In another class, I need to use a MyUserControl, but I would like to declare and use generic UserControl objects. That way, I'll be able to reuse this class even with a new and different user control (let's say MyUserControl2).

So I declared a member of this class as

private static UserControl _userControl;

here is the constructor

public CTPManager(UserControl userControl, string Title, MsoCTPDockPosition Position)
{
    //stuff

    _userControl = userControl;
    _title = Title;
    _position = Position;
}

First question : is it possible to later instantiate the class with this :

MyUserControl newControl = new MyUserControl();
CTPManager newCTP = new CTPManager(newControl, "window title", etc.);

If so, can I call Initialize() method of MyUserControl newControl since I only need to do these two calls inside the CTPManager class :

CustomTaskPaneFactory.CreateCustomTaskPane(typeof(UserControl), _title, _EXCELApp.ActiveWindow)); //-> this one will be ok because of CreateCustomTaskPane signature
_userControl.Initialize //-> that is what I would like to be able to do !

Thank you very much for any answers or advice

Upvotes: 0

Views: 1643

Answers (2)

redlum
redlum

Reputation: 71

Create an interface with the Initialize() method. Implement the interface. Save the control in CTPManager as that interface. Or, if you want to store it as a UserControl, then you could cast it to the type you want:

var init = (InitializerInterface)_userControl;
if (init != null) ...

Upvotes: 0

Alyson Freitas
Alyson Freitas

Reputation: 136

You can use MethodInfo:

//Get the method information using the method info class
 MethodInfo mi = _userControl.GetType().GetMethod("Initialize");

//Invoke the method
mi.Invoke(_userControl, null);

Upvotes: 1

Related Questions