Calling method from different namespace and class

时间:2016-04-04 16:38:16

标签: c# winforms class

I'm trying to put some stuff that I use a lot into separate classes so it's easier to implement when starting a new project.

One of the things that I would like to do, is dynamically create a statusbar on my mainform. I have done this in a previous project and there it worked fine. So I copied the code and I changed the NameSpace for the mainform.

When I run the code it stops at the line

MainForm.Controls.Add(status);

When I look, it says Mainform is null. Other than the Namespace I haven't changed anything. Does anybody have an idea why this is happening?

Thanks Kenneth

//THIS IS THE SEPARATE CLASS    
public class Tools
    {
        public Form MainForm;


        public void setupForm()
        {
            // LINK THE FORM
            MainForm = myNamespace.Form1.MainForm;

            // CREATE A STATUSBAR
            StatusStrip status = new StatusStrip();
            status.Name = "status";

// I'VE REMOVED SOME OF THE DYNAMIC CREATION STUFF FOR READABILITY

            // ADD THE STATUSSTRIP TO THE FORM
            MainForm.Controls.Add(status);
        }

//THIS IS THE MAINFORM
public static Form1 MainForm;
        public myNameSpace.Tools tools;

        private void setupForm()
        {
            this.KeyPreview = true;

            // LINK THE TOOLS CLASS
            tools = new myNameSpace.Tools();

            // SETUP THE FORM
            tools.setupForm();
        }

3 个答案:

答案 0 :(得分:2)

You have to pass a refernece of your main form to the Tools class. You can do this when you initialize tools or when you call the method setupForm. I implemented the second possibility for you:

//the call:
tools.setupForm(this);

//the implementation of the method
private void setupForm(Form1 MainForm)
{
   //your method code
}

答案 1 :(得分:1)

The normal way to separate responsibility is to inject the object you want to affect - not hijack it with a hardcoded reference.

Try injecting the form when you create your tools object:

tools = new myNameSpace.Tools(this);

答案 2 :(得分:0)

Its null because you don't initiate or have a refference to the main window. You just create an alias for the namespace but not for the instance.

Pass the mainWondow as a parameter to the setupForm function. Then it will work.