E_learner
E_learner

Reputation: 3582

How to call a method from another class in c#?

In C#, I have a class with a method like this:

namespace ControlCenter
{
    public partial class Canvas
    {
        ...
        public void display(string itemID)
        {
            ... // here assign some properties to the item
            this.Children.Add(item);
        }
    }
}

This function allows me to add an item to my canvas successfully. Now I want to call this method in another different class like this:

namespace ControlCenter
{
    public class addLayer
    {
        private ControlCenter.Canvas myCanvas = new ControlCenter.Canvas();

        public void add()
        {
            myCanvas.display("1234");
        }
    }
}

But this cannot add any item to my canvas. By debugging, I doubt the problem should be in this line:

this.Children.Add(item);

When calling display method from addLayer class, this is not pointing to the active canvas I guess. But I couldn't find any solution even after mass internet search. Any help?

Upvotes: 0

Views: 5964

Answers (1)

JKennedy
JKennedy

Reputation: 18799

In the example shown I'm guessing canvas is a UserControl and your goal is that when you call the add() method you add an item to that usercontrol. But in the current example in the addlayer class you have created a brand new canvas which you have added an item to. The method does work its just you are adding the child to a brand new canvas which is not displayed. The way around this is to pass the displayed canvas instance to the addlayer class. after the InitialiseComponent() method.

Like so...

namespace ControlCenter
{
    public partial class Canvas : UserControl
    {

        public Canvas
        {
          InitialiseComponent();
          addLayer.myCanvas = this;

        }

        public void display(string itemID)
        {
            ... // here assign some properties to the item
            this.Children.Add(item);
        }
    }
}


namespace ControlCenter
{
    public static class addLayer
    {
        private static ControlCenter.Canvas myCanvas;

        public static void add()
        {
            myCanvas.display("1234");
        }
    }
}

Now when you call addLayer.add() you will add an item to the displayed canvas

Upvotes: 2

Related Questions