0

I have a userControl function that i want to set its action from the parent form.

I've already set userControl button action from that parent form. and it worked like this :

in Form1.cs :

    public Form1()
    {
        InitializeComponent();
        fileManagerLocal1.SetSendButton(SendMethod);
    }
    private void SendMethod()
    {
        //whatever ...
    }

in userControl1.cs :

public void SetSendButton(Action action)
    {
        btnSend.Click += (s, e) => action();
    }

the code up works great. but what i need is how do i set a Function action ..

in Form1.cs

public Form1()
    {
        InitializeComponent();
        fileTransfer1.RefreshLocalFM(RefreshFM);
    }

 public void RefreshFM()
    {
        fileManagerLocal1.btnRefresh.PerformClick();
    }

in userControl1.cs

 public void RefreshLocalFM(Action action)
    {
        action(); // what should be in here ?
    }

thanks in advance. :)

2
  • 1
    If you need to take a function that returns a parameter instead of void then consider using Func/Func<T> instead of Action/Action<T>. Mar 18, 2012 at 2:56
  • @KasperHoldum i don't want that function to return any value .. i need to know what should i write in RefresLocalFM(Action action) Mar 18, 2012 at 5:28

2 Answers 2

1

It's not clear to me what you mean by "set a Function action". Do you want to call that function immediately within the context of the controller? in that case the code you provided is correct. If on the other hand you want to configure the user control to use the provided action in some later code, then you need to store that Action as follows

in userControl1

Action externalFunction = null;
public void RefreshLocalFM(Action action)
    {
        externalFunction = action;
    }

// later code
private void someMethod()
{
   externalFunction();
}

I hope I understood you correctly..

1

I've figured it out a solution ..

in Form1.cs :

public Form1()
{
    InitializeComponent();
    fileTransfer1.refreshAction = new Action (RefreshFM);
    //let's say refreshAction is a public action variable in fileTransfer1 class
}

public void RefreshFM()
{
    fileManagerLocal1.btnRefresh.PerformClick();
}

in userControl1.cs:

public Action refreshAction;
//then it can be called from any place.

private void RefreshLocalFM()
{
    refreshAction.Invoke(); //this fires the action that we initialized from form1.cs
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.