Jana
Jana

Reputation: 3

How can i call method from usercontrol from another usercontrol using c#?

I have two usercontrols: UserControl1 and UserControl2. UserControl1 have a Update() method.

I need call UserControl2 in the call UserControl1 Update() method.How can it?

Upvotes: 0

Views: 165

Answers (3)

Sven M.
Sven M.

Reputation: 509

You could also use System.Action like so even making the parameter of UserControleOne optional.

    class UserControlOne
    {
        public void Update(Action updateAction = null)
        {
            updateAction?.Invoke(); # you could also write updateAction();
        }
    }

    class UserControlTwo
    {
        public void Update()
        {
            Console.WriteLine("Updated");
            Console.ReadKey();
        }
    }

    class Program
    {
        static void Main(String[] args)
        {
            // calling exmaple 1
            UserControlOne uc = new UserControlOne();
            UserControlTwo uc2 = new UserControlTwo();
            uc.Update(uc2.Update);

            // calling example 2
            UserControlOne anotherUserControl = new UserControlOne();
            anotherUserControl.Update();
        }
    }

Upvotes: 1

Jeremy Thompson
Jeremy Thompson

Reputation: 65672

You need to pass the instance of the first User Control into the second:

UserControl1 uc1 = new UserControl1();
UserControl2 uc2 = new UserControl2(uc1);

....
// Set the uc1 object to a private member variable in uc2 in the constructor, then..

//With the object of uc1 in uc2, update it
uc1.Update();

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222682

If you want to access method using object of Usercontrol, you have to register it like this

UserControl1 uc1 = new UserControl1();
uc1.Update();

Upvotes: 0

Related Questions