Search code examples
c#winformsuser-controls

How to call a method from a UserControl class?


I have a Windows Forms app and I would like to call a method in a UserControl class.

My method is placed in Desktop:

public Desktop(StringWrapper stringWrapper, AppConfigManager appConfigManager, RecoveryManager recoveryManager, IProfileManager profileManager, IScanPerformer scanPerformer, IScannedImagePrinter scannedImagePrinter)
{ 
  public void ScanDefault()
   {
     if (profileManager.DefaultProfile != null)
      {
        scanPerformer.PerformScan(profileManager.DefaultProfile, new ScanParams(), this, notify, ReceiveScannedImage());
        Activate();
      }
      else if (profileManager.Profiles.Count == 0)
      {
         ScanWithNewProfile();
      }
      else
      {
         ShowProfilesForm();
      }
   }
}

In the same folder I have created a User Control class:

public partial class UserControlTest : UserControl
{
    public UserControlTest()
    {
        InitializeComponent();
    }
}

In this UserControlTest I would like to call a ScanDefault method.


Solution

  • ScanDefault() is an inline function.

    It's like a local variable.

    You can't call it from outside the scope of Desktop().

    To call it, you must make it as a class method and add parameters you want to use in the signature.

    public Desktop(StringWrapper stringWrapper,
                   AppConfigManager appConfigManager,
                   RecoveryManager recoveryManager,
                   IProfileManager profileManager,
                   IScanPerformer scanPerformer,
                   IScannedImagePrinter scannedImagePrinter)
    {
      ScanDefault(profileManager, scanPerformer);
    }
    
    public void ScanDefault(IProfileManager profileManager, IScanPerformer scanPerformer)
    {
      // ...
    }